c++ - LUA & C++:如何在 LUA 代码中正确使用 C++ 函数
问题描述
我目前正在学习在 C++ 代码中使用 LUA。我到了无法弄清楚如何在 LUA 代码中使用 C++ 函数的地步。
我想在 C++ 中创建简单的函数,然后在 LUA 中使用它。我的方法如下(取自一些教程):
在 main.cpp 中:
void write(const char* str) {
std::cout<<str<<std::endl;
}
static int l_write(lua_State* L) {
const char* str = lua_tostring(L, 1); // get function argument
write(str); // calling C++ function with this argument...
return 0; // nothing to return!
}
int main(){
lua_State* L = luaL_newstate();
luaL_openlibs(L); // load default Lua libs
if (luaL_loadfile(L, "test.lua")) {
std::cout<<"Error loading script"<<std::endl;
}
lua_pushcfunction(L, l_write);
lua_setglobal(L, "write"); // this is how function will be named in Lua
lua_pcall(L, 0, 0, 0); // run script
}
在 test.lua 我有:
write("Hello, world!")
write("The square root of 2 is "..math.sqrt(2))
x = 42
write("We can use variables too, x = "..x)
问题出现在这段代码的最开始:我什至无法加载脚本luaL_loadfile(L, "test.lua")
返回值 7(这是因为我检查了 NIME_AGAIN 7 /* 暂时没有资源 */)。
只要我不使用我的自定义 c++ 函数,其他一切都可以正常工作。我可以正常从 LUA 文件中加载值,可以执行函数等。
我想LUA在读取文件后已经编译它然后找出不存在的函数名称,即“write”并在读取这个文件的情况下返回错误,这可能吗?如果是这样如何解决这个问题,以及如何正确使用这个功能?
解决方案
嗯,伙计们。这很奇怪,但我做过lua_pop(L, 1)
一次,运行然后删除它,现在它工作得很好哦
推荐阅读
- huawei-mobile-services - 华为手机推送有时候延迟太长,有什么解决办法吗?
- asp.net-core - 如何使用 ViewModel 值设置 KendoComboBox(jquery UI) 值?
- python - IBapi想读取和使用IBapi类生成的错误码
- c++ - C++ 类中的成功回调 Emscripten FETCH API
- r - “错误:条件‘partyd’与‘snames’参数中的集合名称不匹配。”
- regex - 正则表达式根据先前的匹配进行匹配
- javascript - getComputedStyle(element).getPropertyValue("--varName") 在 Firefox 中不起作用
- r - Shiny - 更改 DT 表中的列名以存储为 reactiveVal
- java - android studio java web服务控制每45秒
- netty - 当响应时间超过 requestReadTimeoutSeconds 时,KTor 将终止 GET 请求