Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.InteropServices;
- namespace CallingLua
- {
- public static class LuaBridge
- {
- [DllImport("lua53.dll", EntryPoint = "luaL_newstate", CallingConvention = CallingConvention.Cdecl)]
- public static extern IntPtr LuaL_NewState();
- [DllImport("lua53.dll", EntryPoint = "luaL_openlibs", CallingConvention = CallingConvention.Cdecl)]
- public static extern void LuaL_OpenLibs(IntPtr luaState);
- [DllImport("lua53.dll", EntryPoint = "luaL_loadfilex", CallingConvention = CallingConvention.Cdecl)]
- public static extern int LuaL_LoadFileX(IntPtr luaState, IntPtr filename, IntPtr mode);
- [DllImport("lua53.dll", EntryPoint = "lua_tolstring", CallingConvention = CallingConvention.Cdecl)]
- public static extern IntPtr Lua_ToLString(IntPtr luaState, int index, IntPtr size);
- [DllImport("lua53.dll", EntryPoint = "lua_settop", CallingConvention = CallingConvention.Cdecl)]
- public static extern void Lua_SetTop(IntPtr luaState, int n);
- [DllImport("lua53.dll", EntryPoint = "lua_pcallk", CallingConvention = CallingConvention.Cdecl)]
- public static extern int Lua_PCallK(IntPtr luaState, int nArgs, int nRet, int errIndex, int boh, IntPtr boh2);
- public static void Lua_Pop(IntPtr luaState, int n)
- {
- Lua_SetTop(luaState, -n - 1);
- }
- public static int Lua_PCall(IntPtr luaState, int nArgs, int nRet, int errIndex)
- {
- return Lua_PCallK(luaState, nArgs, nRet, errIndex, 0, IntPtr.Zero);
- }
- }
- public class Lua
- {
- private IntPtr luaState;
- public Lua()
- {
- luaState = LuaBridge.LuaL_NewState();
- if (luaState == IntPtr.Zero)
- throw new Exception("Unable to initialize Lua VM");
- LuaBridge.LuaL_OpenLibs(luaState);
- }
- private string GetError()
- {
- IntPtr cStr = LuaBridge.Lua_ToLString(luaState, -1, IntPtr.Zero);
- string errorMessage = Marshal.PtrToStringAnsi(cStr);
- LuaBridge.Lua_Pop(luaState, 1);
- return errorMessage;
- }
- public void LoadFile(string filename)
- {
- IntPtr cFilename = Marshal.StringToHGlobalAnsi(filename);
- int ret = LuaBridge.LuaL_LoadFileX(luaState, cFilename, IntPtr.Zero);
- Marshal.FreeHGlobal(cFilename);
- if (ret != 0)
- {
- throw new Exception(GetError());
- }
- }
- public void Run(int nArgs = 0, int nRet = 0, int errIndex = 0)
- {
- int ret = LuaBridge.Lua_PCall(luaState, nArgs, nRet, errIndex);
- if (ret != 0)
- {
- throw new Exception(GetError());
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment