(1)将要调用的函数封装成一个模块
例如我们要用C封装一个数学模块给lua调用,lua中调用的代码为
sum = mymath.add(1, 3)
sub = mymath.sub(4, 2)
print(sum, sub)
CC代码为:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include "lua.hpp"
#include "lauxlib.h"
#include "lualib.h"
int add(lua_State* L)
{
int a = lua_tointeger(L, 1);
int b = lua_tointeger(L, 2);
lua_pushinteger(L, a + b);
return 1;
}
int sub(lua_State* L)
{
int a = lua_tointeger(L, 1);
int b = lua_tointeger(L, 2);
lua_pushinteger(L, a - b);
return 1;
}
static const luaL_Reg mymathlib[] = {
{"add", add},
{"sub", sub},
{NULL, NULL}
};
int fopen_mymath(lua_State* L)
{
luaL_newlib(L, mymathlib);
return 1;
}
int main()
{
lua_State* L = luaL_newstate(); /* create state */
if (L == NULL) {
printf("lua state build error.\n");
return 1;
}
luaL_openlibs(L);
luaL_requiref(L, "mymath", fopen_mymath, 1); //第四个参数1是生成到全局作用域中
luaL_dofile(L, "tfunc.lua");
std::cin.get();
lua_close(L);
return 0;