我决定用Lua添加脚本.我已下载并编译了解释器.它工作正常,但是当我想使用os.*或string.*libs中的任何函数时,它说"attemt to index global'os'(一个零值)"
这是我的代码,应该可以工作,但它没有:
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
extern "C" {
#include "..\liblua\lua.h"
#include "..\liblua\lualib.h"
#include "..\liblua\lauxlib.h"
}
int main(int argc, TCHAR* argv[])
{
lua_State *LuaVM = luaL_newstate();
lua_pushcfunction(LuaVM,luaopen_base);
lua_call(LuaVM,0,0);
lua_pushcfunction(LuaVM,luaopen_math);
lua_call(LuaVM,0,0);
lua_pushcfunction(LuaVM,luaopen_string);
lua_call(LuaVM,0,0);
lua_pushcfunction(LuaVM,luaopen_table);
lua_call(LuaVM,0,0);
int error;
lua_pushstring(LuaVM,"Ver 0.525.5");
lua_setglobal(LuaVM,"Version");
while (true)
{
string strCode;
getline(cin,strCode);
error = luaL_loadbuffer(LuaVM,strCode.c_str(),strCode.length(),"") ||
lua_pcall(LuaVM,0,0,0);
if (error)
{
cout<< lua_tostring(LuaVM,-1)<<endl;
lua_pop(LuaVM,1);
}
}
lua_close(LuaVM);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它出什么问题了?
在Lua 5.2中,标准luaopen_*函数不设置相应的全局变量.
为什么不复制和调整代码linit.c或只是调用luaL_openlibs?
否则,做他们做的事:呼吁luaL_requiref每个luaopen_*功能.
见http://www.lua.org/source/5.2/linit.c.html#luaL_openlibs.