我正在尝试在C ++中使用lua状态,我需要从C ++传递一个str,但是当我尝试调用我在lua中编写的函数时,我得到了错误 试图调用nil值。它直接编译到lua环境中,但是当我在i中键入表达式时会得到错误。
int main(int argc, char** argv){
lua_State *L;
L = luaL_newstate();
string buff;
const char* finalString;
luaL_openlibs(L);
luaL_dofile(L,argv[1]);
getline(cin, buff);
lua_getglobal(L, "InfixToPostfix");
lua_pushstring (L, buff.c_str());
lua_pcall(L, 1, 1, 0);
finalString = lua_tostring(L, -1);
printf("%s\n", finalString);
lua_close(L);
}
来自lua文件:
function InfixToPostfix(str)
print("before for loop")
for i in string.gmatch(str, "%S+") do
在显示错误
之前它不会到达打印输出答案 0 :(得分:1)
以下对我来说很合适:
#include <iostream>
#include <string>
#include <lua.hpp>
int main(int argc, char** argv)
{
lua_State *L;
L = luaL_newstate();
luaL_openlibs(L);
if (argc != 2)
{
std::cerr << "Usage: " << argv[0] << " script.lua\n";
return 1;
}
if ( luaL_dofile(L,argv[1]) != 0 )
{
std::cerr << lua_tostring(L, -1) << '\n';
return 1;
}
std::string buff;
std::getline(std::cin, buff);
lua_getglobal(L, "InfixToPostfix");
lua_pushstring (L, buff.c_str());
if ( lua_pcall(L, 1, 1, 0) != 0)
{
std::cerr << lua_tostring(L, -1) << '\n';
return 1;
}
if ( !lua_isstring(L, -1) )
{
std::cerr << "Error: Return value cannot be converted to string!\n";
return 1;
}
const char * finalString = lua_tostring(L, -1);
std::cout << finalString << '\n';
lua_close(L);
}
function InfixToPostfix(str)
print("before for loop")
for i in string.gmatch(str, "%S+") do
print(i)
end
return "Something"
end
对于C ++部分,您还可以使用Selene库。这大大减少了所需的代码量,也无需手动错误检查。
#include <iostream>
#include <string>
#include <selene.h>
int main(int argc, char** argv)
{
sel::State L{true};
if (argc != 2)
{
std::cerr << "Usage: " << argv[0] << " script.lua\n";
return 1;
}
L.Load(argv[1]);
std::string buff;
std::getline(std::cin, buff);
std::string finalString = L["InfixToPostfix"](buff);
std::cout << finalString << '\n';
}