Created
March 29, 2013 02:27
-
-
Save topin27/5268334 to your computer and use it in GitHub Desktop.
C++与Lua之间的相互调用接口
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*先是C++调用Lua。 | |
*/ | |
extern "C" { | |
#include "lua.h" | |
#include "lualib.h" | |
#include "lauxlib.h" | |
} | |
#include <cstdio> | |
using std::printf; | |
int main() | |
{ | |
lua_State* L = luaL_newstate(); | |
luaL_openlibs(L); | |
printf("Press any key to run the \'add.lua\' file!\n"); | |
luaL_dofile(L, "add.lua"); | |
lua_getglobal(L, "add"); | |
lua_pushnumber(L, 10); | |
lua_pushnumber(L, 20); | |
lua_pcall(L, 2, 1, 0); | |
int sum = (int)lua_tonumber(L, -1); | |
printf("The stack size is %d\n", lua_gettop(L)); | |
lua_pop(L, 1); | |
printf("The result is %d\n", sum); | |
lua_close(L); | |
return 1; | |
} | |
/*相应的lua文件为: | |
function add(a, b) | |
return a + b | |
end | |
*/ | |
///////////////////////////////////////////////////////////////////////////// | |
/*然后是使用C++给Lua写扩展库 | |
*/ | |
extern "C" { | |
#include "lua.h" | |
#include "lualib.h" | |
#include "lauxlib.h" | |
} | |
namespace { | |
extern "C" int l_add2(lua_State* L) | |
{ | |
double op1 = lua_tonumber(L, 1); | |
double op2 = lua_tonumber(L, 2); | |
lua_pushnumber(L, op1 + op2); | |
return 1; | |
} | |
extern "C" int l_sub2(lua_State* L) | |
{ | |
double op1 = lua_tonumber(L, 1); | |
double op2 = lua_tonumber(L, 2); | |
lua_pushnumber(L, op1 - op2); | |
return 1; | |
} | |
const struct luaL_Reg mylib[] = { | |
{"myadd", l_add2}, | |
{"mysub", l_sub2}, | |
{NULL, NULL} | |
}; | |
} | |
//该C库的唯一入口函数。其函数签名等同于上面的注册函数。见如下几点说明: | |
//1. 我们可以将该函数简单的理解为模块的工厂函数。 | |
//2. 其函数名必须为luaopen_xxx,其中xxx表示library名称。Lua代码require "xxx"需要与之对应。 | |
//3. 在luaL_register的调用中,其第一个字符串参数为模块名"xxx",第二个参数为待注册函数的数组。 | |
//4. 需要强调的是,所有需要用到"xxx"的代码,不论C还是Lua,都必须保持一致,这是Lua的约定, | |
// 否则将无法调用。 | |
extern "C" int luaopen_mylib(lua_State* L) | |
{ | |
//luaL_register(L, "mylib", mylib); //这个是5.1以前的调用方式 | |
luaL_newlib(L, mylib); //通过require来使用 | |
return 1; | |
} | |
/*相应的Lua文件为: | |
local lib = require "mylib" | |
print(lib.myadd(1, 2)) | |
print(lib.mysub(3, 2)) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment