In C++, using luabind, call function defined in lua file?

旧时模样 提交于 2019-12-13 05:16:02

问题


Say I have a lua file:

--functions.lua
function testadd(a, b) 
    return a+b
end

How would I use luabind to load that file, and call that function- something like:

//test.cpp
extern "C" {
    #include "lua.h"
    #include "lualib.h"
    #include "lauxlib.h"
}
#include <luabind/luabind.hpp>
#include <luabind/function.hpp> 

int main() {
    lua_State *myLuaState = lua_open();
    luaL_openlibs(myLuaState);
    luaL_loadfile(myLuaState, "functions.lua");
    luabind::open(myLuaState);
    int value = luabind::call_function<int>(myLuaState, "testadd", 2, 3);
    lua_close(myLuaState);
}

But this returns an error: terminate called after throwing an instance of 'luabind::error' what(): lua runtime error Aborted

So, what is the proper syntax for doing what I want to do? (From the looks of the error it seems to be a problem with the syntax in the lua file, but I don't think it is...)


回答1:


You probably want to call luaL_dofile instead of luaL_loadfile here.



来源:https://stackoverflow.com/questions/6314136/in-c-using-luabind-call-function-defined-in-lua-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!