lua的packages实现

complex.lua
local P = {}                    --使用局部变量临时储存对象
P.i = {r=0, i=1}                --初始化对象参数

--packages的私有成员,只要使用local声明一个方法即可
local function checkComplex(c)            
    if not ((type(c) == "table") and tonumber(c.r) and tonumber(c.i)) then
    error("bad complex number", 3)
    end
end

function P.new(r, i)
    return {r=r, i=i}
end

function P.add(c1, c2)
    checkComplex(c1);
    checkComplex(c2);
    return P.new(c1.r + c2.r, c1.i + c2.i)
end

function P.sub(c1, c2)
    return P.new(c1.r - c2.r, c1.i - c2.i)
end

function P.mul(c1, c2)
    return P.new(c1.r*c2.r - c1.i*c2.i, c1.r*c2.i + c1.i*c2.r)
end

function P.inv(c1, c2)
    local n = c.r^2 + c.i^2
    return P.new(c.r/n, -c.i/n)
end

return P                        --记得返回该对象本身

lua_main.lua
complex = require "complex"        --使用文件作为对象的返回值
c = complex.add(complex.i, complex.new(10, 20))
print(c.i)

你可能感兴趣的:(Lua编程,lua使用技巧)