Guest User

Untitled

a guest
May 20th, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. using System;
  2. using System.Runtime.InteropServices;
  3.  
  4. namespace CallingLua
  5. {
  6. public static class LuaBridge
  7. {
  8. [DllImport("lua53.dll", EntryPoint = "luaL_newstate", CallingConvention = CallingConvention.Cdecl)]
  9. public static extern IntPtr LuaL_NewState();
  10.  
  11. [DllImport("lua53.dll", EntryPoint = "luaL_openlibs", CallingConvention = CallingConvention.Cdecl)]
  12. public static extern void LuaL_OpenLibs(IntPtr luaState);
  13.  
  14. [DllImport("lua53.dll", EntryPoint = "luaL_loadfilex", CallingConvention = CallingConvention.Cdecl)]
  15. public static extern int LuaL_LoadFileX(IntPtr luaState, IntPtr filename, IntPtr mode);
  16.  
  17. [DllImport("lua53.dll", EntryPoint = "lua_tolstring", CallingConvention = CallingConvention.Cdecl)]
  18. public static extern IntPtr Lua_ToLString(IntPtr luaState, int index, IntPtr size);
  19.  
  20. [DllImport("lua53.dll", EntryPoint = "lua_settop", CallingConvention = CallingConvention.Cdecl)]
  21. public static extern void Lua_SetTop(IntPtr luaState, int n);
  22.  
  23. [DllImport("lua53.dll", EntryPoint = "lua_pcallk", CallingConvention = CallingConvention.Cdecl)]
  24. public static extern int Lua_PCallK(IntPtr luaState, int nArgs, int nRet, int errIndex, int boh, IntPtr boh2);
  25.  
  26. public static void Lua_Pop(IntPtr luaState, int n)
  27. {
  28. Lua_SetTop(luaState, -n - 1);
  29. }
  30.  
  31. public static int Lua_PCall(IntPtr luaState, int nArgs, int nRet, int errIndex)
  32. {
  33. return Lua_PCallK(luaState, nArgs, nRet, errIndex, 0, IntPtr.Zero);
  34. }
  35. }
  36.  
  37. public class Lua
  38. {
  39. private IntPtr luaState;
  40. public Lua()
  41. {
  42. luaState = LuaBridge.LuaL_NewState();
  43. if (luaState == IntPtr.Zero)
  44. throw new Exception("Unable to initialize Lua VM");
  45.  
  46. LuaBridge.LuaL_OpenLibs(luaState);
  47. }
  48.  
  49. private string GetError()
  50. {
  51. IntPtr cStr = LuaBridge.Lua_ToLString(luaState, -1, IntPtr.Zero);
  52. string errorMessage = Marshal.PtrToStringAnsi(cStr);
  53. LuaBridge.Lua_Pop(luaState, 1);
  54. return errorMessage;
  55. }
  56.  
  57. public void LoadFile(string filename)
  58. {
  59. IntPtr cFilename = Marshal.StringToHGlobalAnsi(filename);
  60. int ret = LuaBridge.LuaL_LoadFileX(luaState, cFilename, IntPtr.Zero);
  61. Marshal.FreeHGlobal(cFilename);
  62. if (ret != 0)
  63. {
  64. throw new Exception(GetError());
  65. }
  66. }
  67.  
  68. public void Run(int nArgs = 0, int nRet = 0, int errIndex = 0)
  69. {
  70. int ret = LuaBridge.Lua_PCall(luaState, nArgs, nRet, errIndex);
  71. if (ret != 0)
  72. {
  73. throw new Exception(GetError());
  74. }
  75. }
  76. }
  77. }
Add Comment
Please, Sign In to add comment