Lua版本:5.2.3
一 C++ 调用Lua
1 目录结构
CppCallLua
{
main.cpp
script{
test.lua
}
lualia{
lua.h
lualib.h
laux.lib.h
luaconf.h
liblua.a
}
}
2 代码
#include <iostream>
extern "C"
{
#include "lualib/lua.h"
#include "lualib/lualib.h"
#include "lualib/lauxlib.h"
}
using namespace std;
int main()
{
lua_State* L = luaL_newstate() ;
luaopen_base(L) ;// 不知道为什么这里使用luaL_openlibs(L)会报错
luaL_dofile(L, "script/test.lua") ;
lua_getglobal(L, "add") ;
lua_pushnumber(L, 1) ;
lua_pushnumber(L, 2) ;
lua_pcall(L, 2, 1, 0) ;
int sum = (int)lua_tonumber(L, -1) ;
lua_pop(L, -1) ;
lua_close(L) ;
cout << "1 + 2 = " << sum << endl;
return 0 ;
}
extern "C"
{
#include "lualib/lua.h"
#include "lualib/lualib.h"
#include "lualib/lauxlib.h"
}
using namespace std;
int main()
{
lua_State* L = luaL_newstate() ;
luaopen_base(L) ;// 不知道为什么这里使用luaL_openlibs(L)会报错
luaL_dofile(L, "script/test.lua") ;
lua_getglobal(L, "add") ;
lua_pushnumber(L, 1) ;
lua_pushnumber(L, 2) ;
lua_pcall(L, 2, 1, 0) ;
int sum = (int)lua_tonumber(L, -1) ;
lua_pop(L, -1) ;
lua_close(L) ;
cout << "1 + 2 = " << sum << endl;
return 0 ;
}
function add(x, y)
return x + y
end
return x + y
end
二 lua调用C++
lua调用C++函数还是以C++为主体,在C++中使用运行Lua脚本,在Lua脚本中又调用C++自己实现的函数。
实际上就C++通过Lua脚本调用自己的函数。
1 目录结构
LuaCallCpp
{
main.cpp
test.lua
lualia{
lua.h
lualib.h
laux.lib.h
luaconf.h
liblua.a
}
}
2 代码
// main.cpp
#include <iostream>
extern "C"
{
#include "lualib/lua.h"
#include "lualib/lualib.h"
#include "lualib/lauxlib.h"
}
using namespace std;
lua_State* L ;
static int average(lua_State *L)
{
// num of args
int n = lua_gettop(L) ;
double sum = 0 ;
int i = 0 ;
for ( i = 1; i <= n; ++i)
{
sum += lua_tonumber(L, i) ;
}
// push the average
lua_pushnumber(L, sum / n) ;
// push the sum
lua_pushnumber(L, sum) ;
return 2;
}
int main()
{
L = luaL_newstate() ;
luaopen_base(L) ;
// register function
lua_register(L, "average", average) ;
luaL_dofile(L, "test.lua") ;
lua_close(L) ;
return 0 ;
}
extern "C"
{
#include "lualib/lua.h"
#include "lualib/lualib.h"
#include "lualib/lauxlib.h"
}
using namespace std;
lua_State* L ;
static int average(lua_State *L)
{
// num of args
int n = lua_gettop(L) ;
double sum = 0 ;
int i = 0 ;
for ( i = 1; i <= n; ++i)
{
sum += lua_tonumber(L, i) ;
}
// push the average
lua_pushnumber(L, sum / n) ;
// push the sum
lua_pushnumber(L, sum) ;
return 2;
}
int main()
{
L = luaL_newstate() ;
luaopen_base(L) ;
// register function
lua_register(L, "average", average) ;
luaL_dofile(L, "test.lua") ;
lua_close(L) ;
return 0 ;
}
// test.lua
avg, sum = average(1, 2, 3, 4, 5)
print ("The average is ", avg)
print ("The sum is ", sum)
print ("The average is ", avg)
print ("The sum is ", sum)