C++ 中呼叫 Lua 函式
阿新 • • 發佈:2019-02-10
使用上篇的程式碼
http://blog.csdn.net/huutu/article/details/49594469
在 C++中呼叫 lua 中的函式並處理返回值
main.cpp
#include <stdio.h> #include<windows.h> extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" #include "luaconf.h" } #include "tolua++.h" #include"Student.h" extern int tolua_Student_open(lua_State* tolua_S); int main(int argc, char* argv[]) { lua_State* L = luaL_newstate(); luaL_openlibs(L); tolua_Student_open(L); luaL_dofile(L, "./test.lua"); int top = lua_gettop(L); lua_getglobal(L, "returnsomething"); if (!lua_isfunction(L, -1)) { } lua_pushstring(L, "chenpeng"); lua_pushnumber(L, 22); lua_pcall(L, 2, 2, 0); if (!lua_isnumber(L, -1) || !lua_isstring(L, -2)) { } int age = (int)lua_tonumber(L, -1); const char* name = lua_tostring(L, -2); cout << age << name << endl; lua_settop(L, top); lua_close(L); system("pause"); return 0; }
test.lua
studentB=Student:new() --例項化Student全域性物件 function Run() studentB:Run(); end function Run2(a) studentB:Run2(a); end function show() local b = {} local index for index = 1,10,1 do print(index) end end function returnsomething(name,age) print("name" .. name) print("age" .. age) return name,age end show() Run() Run2(10)