这一个例子就是用来说明如何通过C语言,注册一个static的函数到lua的虚拟机中.然后通过C语言调用lua中的一个函数.lua中的这个函数又会调用C语言中注册的这个函数.
#include <iostream>
#include <lua.hpp>
#pragma comment(lib,"luastatic")
using namespace std;
// 函数定义
static int l_dir(lua_State *L)
{
cout<<"第一个参数"<<luaL_checkstring(L,1)<<endl;
cout<<"第二个参数"<<luaL_checknumber(L,2)<<endl;
cout<<"hi"<<endl;
return 0;
}
static const struct luaL_reg mylib[]={
{"dir",l_dir},
{NULL,NULL}
};
int luaopen_mylib(lua_State *L)
{
luaL_register(L,"mylib",mylib);
return 0;
}
int main()
{
lua_State *L=luaL_newstate();
luaopen_mylib(L);
luaL_dofile(L,"d://test.lua");
// 调用一个函数
lua_getglobal(L,"f");
lua_pushnumber(L,2);
lua_pushnumber(L,3);
lua_pcall(L,2,1,0);
lua_close(L);
return 0;
}
--[[
lua定义出来的文件.
--]]
function f (x, y)
return mylib.dir("string",100)
-- return (x^2*math.sin(y))/(1-x)
end
发表于 @ 2006年06月12日 17:04:00|评论(loading...)|编辑