lua5.1.lib。lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, "script.lua"); lua_pcall(L,0,0,0);
lua_getglobal(L, "varName");
int val = lua_tointeger(L, -1); lua_pop(L,1);
lua_getglobal(L, "funcName");
lua_pushinteger(L, arg1); lua_pushinteger(L, arg2);
lua_pcall(L, 2, 1, 0); // 2參數,1返回值
int ret = lua_tointeger(L, -1); lua_pop(L,1);
需註冊 C 函數獲取值,或用 lua_pushinteger 設置全局表字段。
// C 函數簽名
int c_func(lua_State *L) {
int arg = luaL_checkinteger(L, 1);
lua_pushinteger(L, arg * 2); return 1;
}
// 註冊
lua_pushcfunction(L, c_func);
lua_setglobal(L, "c_func");
參考原文代碼:lua.lua 定義變量與函數,C++ 主程序演示雙向調用,輸出版本字串。