luaCpp

1.手动绑定 2dx3.0

参考:http://www.tairan.com/archives/5493

1.c++里注册 lua 要调用的方法

auto engine = LuaEngine::getInstance();

RegisterFoo(engine->getLuaStack()->getLuaState());

engine->executeScriptFile("src/fun.lua");

在 fun.h 里面声明了一些 c 方法

2. fun.lua文件

function Foo:speak()
    print("Hello, I am a Foo")
end
 
local foo = Foo.new("fred")         --创建对象
local m = foo:add(3, 4)             --调用对象方法
 
print(m)
 
foo:speak()
 
Foo.add_ = Foo.add                  --方法放到本地表中
function Foo:add(a, b)
    return "here comes the magic: " .. self:add_(a, b)
end
 
m = foo:add(9, 8)                   --优先调用 lua 的方法

foo:__gc()                          --销毁对象
 
print(m)
3.fun C++

fun.h

#ifndef Language_Lua_fun_h
#define Language_Lua_fun_h

#include <iostream>
#include <sstream>

class Foo
{
public:
    Foo(const std::string & name) : name(name)
    {
        std::cout << "Foo is born" << std::endl;
    }
    
    std::string Add(int a, int b)
    {
        std::stringstream ss;
        ss << name << ": " << a << " + " << b << " = " << (a+b);
        return ss.str();
    }
    
    ~Foo()
    {
        std::cout << "Foo is gone" << std::endl;
    }
    
private:
    std::string name;
};

//声明一些 C 的方法
int l_Foo_constructor(lua_State * l);
Foo * l_CheckFoo(lua_State * l, int n);
int l_Foo_add(lua_State * l);
int l_Foo_destructor(lua_State * l);
void RegisterFoo(lua_State * l);

#endif
fun.cpp

extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

#include "fun.h"

int l_Foo_constructor(lua_State * l)
{
    const char * name = luaL_checkstring(l, 1);
    Foo ** udata = (Foo **)lua_newuserdata(l, sizeof(Foo *));
    *udata = new Foo(name);
    
    luaL_getmetatable(l, "luaL_Foo");
    lua_setmetatable(l, -2);

    return 1;
}

Foo * l_CheckFoo(lua_State * l, int n)
{
    return *(Foo **)luaL_checkudata(l, n, "luaL_Foo");
}

int l_Foo_add(lua_State * l)
{
    Foo * foo = l_CheckFoo(l, 1);
    int a = luaL_checknumber(l, 2);
    int b = luaL_checknumber(l, 3);
    
    std::string s = foo->Add(a, b);
    lua_pushstring(l, s.c_str());
    
    return 1;
}

int l_Foo_destructor(lua_State * l)
{
    Foo * foo = l_CheckFoo(l, 1);
    delete foo;
    
    return 0;
}

void RegisterFoo(lua_State * l)
{
    luaL_Reg sFooRegs[] =
    {
        { "new", l_Foo_constructor },//lua 对象.方法,对应执行的 c 方法
        { "add", l_Foo_add },
        { "__gc", l_Foo_destructor },
        { NULL, NULL }
    };
    
    luaL_newmetatable(l, "luaL_Foo");
    luaL_register(l, NULL, sFooRegs);
    lua_pushvalue(l, -1);
    
    lua_setfield(l, -1, "__index");
    lua_setglobal(l, "Foo");
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值