从lua 5.2调用ac函数会生成语法错误

Del*_*ake 4 c c++ lua

我一直在努力让lua脚本为我正在进行的小游戏工作,但是lua似乎比它的价值更麻烦.经过大量的谷歌搜索和头发撕裂,我设法让简单的脚本运行,但很快就碰壁了.C函数似乎不想绑定到lua,或者至少不想在绑定后运行.g ++编译c代码而不会发生意外,但lua解释器会生成此语法错误:

LUA ERROR: bin/lua/main.lua:1: syntax error near 'getVersion'
Run Code Online (Sandbox Code Playgroud)

我的C(++)代码:

#include <lua.hpp>

static const luaL_Reg lualibs[] = 
{
    {"base", luaopen_base},
    {"io", luaopen_io},
    {NULL, NULL}
};

void initLua(lua_State* state);
int getVersion(lua_State* state);

int main(int argc, char* argv[])
{
    lua_State* state = luaL_newstate();
    initLua(state);

    lua_register(state, "getVersion", getVersion);

    int status = luaL_loadfile(state, "bin/lua/main.lua");
    if(status == LUA_OK){
        lua_pcall(state, 0, LUA_MULTRET, 0);
    }else{
        fprintf(stderr, "LUA ERROR: %s\n", lua_tostring(state, -1));
        lua_close(state);
        return -1;
    }

    lua_close(state);
    return 0;
}

void initLua(lua_State* state)
{
    const luaL_Reg* lib = lualibs;
    for (; lib->func != NULL; lib ++)
    {
        luaL_requiref(state, lib->name, lib->func, 1);
        lua_settop(state, 0);
    };
    delete lib;
}
int getVersion(lua_State* state)
{
    lua_pushnumber(state, 1);
    return 1;
};
Run Code Online (Sandbox Code Playgroud)

Lua代码:

print getVersion()
Run Code Online (Sandbox Code Playgroud)

小智 6

print是一个功能.由于它的参数既不是表构造函数也不是字符串文字,您必须使用()以下方法调用它:

print(getVersion())
Run Code Online (Sandbox Code Playgroud)

在这里阅读有趣的手册.