#include "luna.h"
template<class T> class luna
{
public:
static void Register(lua_State *L)
{
lua_pushcfunction(L, &luna<T>::construct);
lua_setglobal(L, T::classname);
luaL_newmetatable(L, T::classname);
int meta_tb = lua_gettop(L);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, &luna<T>::gc_obj);
lua_settable(L, meta_tb);
}
static int construct(lua_State *L)
{
T* obj = new T(L);
lua_newtable(L);
int tb1 = lua_gettop(L);
lua_pushnumber(L, 0);
T** pp = (T**)lua_newuserdata(L, sizeof(T*));
*pp = obj;
luaL_getmetatable(L, T::classname);
lua_setmetatable(L, -2);
lua_settable(L, tb1);
for (int i=0; T::function[i].name; i++)
{
lua_pushstring(L, T::function[i].name);
lua_pushnumber(L, i);
lua_pushcclosure(L, &luna<T>::thunk , 1);
lua_settable(L,tb1);
}
return 1;
}
static int thunk(lua_State *L)
{
int i = (int)lua_tonumber(L, lua_upvalueindex(1));
lua_pushnumber(L, 0);
lua_gettable(L, 1);
T* p = *((T**)luaL_checkudata(L, -1, T::classname));
lua_remove(L, -1);
return (p->*(T::function[i].mfunc))(L);
}
static int gc_obj(lua_State *L)
{
T* p = *((T**)luaL_checkudata(L, -1, T::classname));
if (p)
delete p;
return 0;
}
struct RegType
{
const char *name;
int (T::*mfunc)(lua_State *);
};
};
class Base
{
public:
Base() {}
~Base() {}
int add(int a, int b)
{ return a + b; }
};
class Foo :public Base
{
public:
Foo(lua_State *L) { printf("call Foo constructor\n"); }
~Foo() { printf("call Foo destructor\n"); }
int foo(lua_State *L) { printf("in foo function\n"); return 0; }
int get(lua_State *L) { printf("in get function\n"); return 0; }
int n_add(lua_State *L)
{
int a = NULL;
int b = NULL;
a = (int)luaL_checknumber(L, -2);
b = (int)luaL_checknumber(L, -1);
double result = add(a, b);
lua_pushnumber(L, result);
// int index = lua_gettop(L);
// printf("index=%d",index);
return 1;
}
static const char classname[];
static const luna<Foo>::RegType function[];
private:
int m_value;
};
const char Foo::classname[] = "Foo";
const luna<Foo>::RegType Foo::function[] =
{
{ "foo", &Foo::foo},
{ "get", &Foo::get},
{ "add", &Foo::n_add},
{ NULL , NULL }
};
int main()
{
lua_State *L = lua_open();
luaopen_base(L);
luna<Foo>::Register(L);
luaL_dofile(L, "test.lua");
lua_close(L);
return 0;
}
没有合适的资源?快使用搜索试试~ 我知道了~
将c++类导出到lua脚本实例
共9个文件
h:1个
lua:1个
bak:1个
5星 · 超过95%的资源 需积分: 42 22 下载量 55 浏览量
2008-07-28
10:27:52
上传
评论
收藏 9KB RAR 举报
温馨提示
将c++类导出到lua脚本实例
资源推荐
资源详情
资源评论
收起资源包目录
luaWipper.rar (9个子文件)
luaWipper 7.25
luna.h 97B
test.lua 62B
test.lua.bak 63B
luaWipper.dsw 524B
luaWipper.cpp 2KB
luaWipper.ncb 49KB
luaWipper.dsp 4KB
luaWipper.opt 53KB
luaWipper.plg 1KB
共 9 条
- 1
资源评论
- pingfang9112014-05-30还行 不过我觉得 意义不大 还不如只注册 函数 然后再 用表实现 感觉还方便一点
- 怀着梦想的-凡人2014-03-31还行吧, 不过网上很多资料都是同样的,希望多写点lua5.2的
- 天地蜉蝣2012-05-15的确是个不错的入门例子
- boyhs12013-07-22还不错,对于初学者还是有点用的。
anran2008
- 粉丝: 4
- 资源: 5
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功