您的位置:首页 > 编程语言 > Lua

Lua5.3.4测试代码

2017-10-29 22:30 316 查看
写了一点简单的程序测试学习一下Lua^_^,Lua做成了动态链接库,使用C++调Lua,里面还有一个调C写的DLL,也就是C++调用Lua虚拟机,然后Lua再调用C写的DLL2333

luatest.cpp

#include<iostream>
#include<lua.hpp>
using namespace std;

#define execute
//#define load
//#define registercfun

#ifdef registercfun
static int sub(lua_State* L)
{
int a=luaL_checknumber(L,1);
int b=luaL_checknumber(L,2);
lua_pushnumber(L,a-b);
return 1;
}
const char* testcfun="print(c_sub(1,1))";
#endif // registercfun

int main()
{
lua_State *L=luaL_newstate();
if(L)
{
luaL_openlibs(L);
}
else
{
cout<<"creat luastate falied!\n";
return 0;
}

lua_newtable(L);//新建表
lua_pushstring(L,"name");
lua_setfield(L,-2,"lisi");

#ifdef execute

if(luaL_loadfile(L,"exectest.lua")||lua_pcall(L,0,0,0))
{
cout<<"file load err!\n";
lua_close(L);
return -1;
}
if(luaL_dofile(L,"exectest.lua"))
{
cout<<"file execute err!\n";
}
#endif // execute

#ifdef load
if(luaL_loadfile(L,"test.lua")||lua_pcall(L,0,0,0))
{
cout<<"file load err!\n";
lua_close(L);
return -1;
}

lua_getglobal(L,"str");
cout<<"the str is: "<<luaL_checkstring(L,-1)<<"\n";

lua_getglobal(L,"tbl");
lua_getfield(L,-1,"name");
lua_getfield(L,-2,"id");

cout<<"name: "<<luaL_checkstring(L,-2)<<"\n";
cout<<"id: "<<luaL_checknumber(L,-1)<<"\n";

lua_getglobal(L,"add");
lua_pushnumber(L,1);
lua_pushnumber(L,1);
if(lua_pcall(L,2,1,0))
{
const char* errmsg=lua_tostring(L,-1);
cout<<errmsg<<"\n";
lua_close(L);
return -1;
}
cout<<"1+1="<<luaL_checknumber(L,-1)<<"\n";
#endif // load

#ifdef registercfun
lua_pushcfunction(L,sub);
lua_setglobal(L,"c_sub");
if (luaL_dostring(L,testcfun))
printf("Failed to invoke.\n");

#endif // registercfun

lua_close(L);
return 0;
}


exectest.lua

require ("module")
print(module.constant)
module.fun1()
--module.fun2()
module.fun3()
mylib=require("MyLib")
mylib.hello()


module.lua

module={}
module.constant="这是一个常量"
function module.fun1()
print("这是一个公有函数")
end
local function fun2()
io.write("这是一个私有函数\n")
end
function module.fun3()
fun2()
end
return module


test.lua

str="this is an string"
tbl={name="zhangsan",id=140410}
function add(a,b)
return a+b
end


然后是C库的:

extern "C" {
#include "lua.hpp"
}

extern "C" int hello(lua_State* L) {
printf("hello");
return 0;
}

static const luaL_Reg myLib[] =
{
{ "hello", hello },
{ NULL, NULL }
};

#ifdef _WIN32
extern "C" __declspec(dllexport) int luaopen_MyLib(lua_State* L)
{
#pragma message ("win32")
#else
extern "C"  int luaopen_MyLib(lua_State* L)
{
#pragma message ("unix")
#endif // _WIN32
luaL_newlib(L, myLib);
return 1;
};


之前我链接C库的时候一直不成功,因为用的dofile所以也没看到具体错误提示,后来直接用Lua解释器执行才看到错误:

multiple Lua VMs detected

因为我原来用的是静态链接Lua,这样解释器是静态链接的,而C的DLL也是静态链接的,这样就出现了两个Lua虚拟机。。。。。后来我把Lua编译成动态库,然后解释器也变成动态链接Lua,C库也链接动态Lua,这样解释器和DLL就链接到了同一个动态Lua,然后不报错误了。。同理我把测试程序也换成静态库,然后就没问题了。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lua c++ 测试 5-3-4 链接DLL