lua 5.2的 luaL_newlib 的用法

对于Lua 5.2, lua 5.2是2011年发布的。国内使用5.1的居多。
luaL_register 和luaL_openlibs。这些功能大多数都废弃了


luaL_register这个注册c++的库函数,功能被废弃了。新的api luaL_newlib 网上的资料不多。

下面给出一个使用 luaL_newlib的例子来调用c++ 函数

//this is c++ code
#include "stdafx.h"
#include "math.h"

extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
};
//this is callback function for the lua
static int GetSin(lua_State* luaState)
{
float f;
f = (float)luaL_checknumber(luaState, 1);
// f = (float)lua_tonumber(luaState,1);
float v = sinf(f);
lua_pushnumber(luaState,v);
return 1;
}

static const luaL_Reg testlib[] =
{
{
"GetSin",GetSin},
{
NULL,NULL
}
};

int luaopen GetLib(lua_State* L)
{
luaL_newlib(L,testlib);
return 1; //return one value
}


int main(int argc, _TCHAR* argv[])
{
lua_State *L = luaL_newstate();
luaL_requiref(L,"sinlib",luaopen GetLib,1);

int status = luaL_loadfile(L,"cfg.lua"); //load the cfg.lua
lua_pcall(L, 0, 0, 0); //execute the loaded cfg.lua

int top = lua_gettop(L);

double x = 10;
double y = 20;
double z = 0;

lua_getglobal(L, "foo"); 
bool isf = lua_isfunction(L,-1);
lua_pushnumber(L, x); 
lua_pushnumber(L, y); 
//execute the lua function (pass two parameters, return one result
if (lua_pcall(L, 2, 1, 0) != 0)
luaL_error(L, "error running function 'f': %s",
lua_tostring(L, -1));
if (!lua_isnumber(L, -1))
luaL_error(L, "function 'foo' must return a number");
z = lua_tonumber(L, -1);
lua_pop(L, 1);
lua_close(L);

return 0;
}


cfg.lua的代码在这里

function foo(x, y)
  --return (x^2 * math.sin(y))/(1 - x)
  --return x + y
  return sinlib.GetSin(x) + y
end

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值