lua(1)

以后lua系列记录自己的lua学习点滴

--C++代码
int getnumber(int num)
{
return num+1;
}
int cpp_getnum(lua_state* pl)
{
//从栈顶取一个值
int num = (int)lua_tonumber(pl,-1);
lua_pushnumber(pl,getnumber(num));
return 1;
}
main()
{
lua_state* pl = lua_open();
luaopen_base(pl);
lua_register(pl,"cpp_getnum",cpp_getnum);
lua_dofile(pl,"hello.lua");//执行lua脚本
lua_close(pl);
}
--C++代码
--lua脚本 hello.lua
local num=cpp_getnum(10)




lua的闭包
function test()
local i = 0
return function()
i = i+1
return i
end
end
--i是一个闭包变量,因此每次调用的时候,会一直加下去
c1 = test()
c2 = test()--另一个 所以独立与c1


print(c1()) --1
print(c1()) --2
print(c1()) --3
print(c1()) --4
--闭包让代码更清晰好懂


协程
co = coroutine.create(function ()
for i=1,10 do
print("co", i)
coroutine.yield()
end
end)


coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)
coroutine.resume(co)










多重继承


girl = createClassFrom(Human, Programmer, Animal, Female)


function createClassFrom(...)
    -- c为返回值的目标表,为实现多重继承的子类表


    local c = {}
    function c:new(o)
        o = o or {}
        setmetatable(o, {__index = c})
        return o
    end


    local parents = {...}
    setmetatable(c, {__index = function(t, k)
        return search(k, parents)
    end})


    return c
end


local function search(k, tables)
    for i, v in ipairs(tables) do
        if v[k] then
            return v[k]
        end
    end
    return nil
end


元方法
__index
__newindex
_gc
_metatable
__call元方法
function f(tb,x,y)
return x+y+tb.n
end
b = {}
b.__call = f
a = {}
a.n = 100
setmetatable(a,b)
print(a(1,2))


unpack(list,[,i[,j]])
return the elements from the given table. this function is equivelent to
return list[i],list[i+1], . . . ,list[j]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值