lua的packages实现

来源:互联网 发布:黑帽白帽seo技术ppt 编辑:程序博客网 时间:2024/05/08 22:34
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)    endendfunction P.new(r, i)    return {r=r, i=i}endfunction P.add(c1, c2)    checkComplex(c1);    checkComplex(c2);    return P.new(c1.r + c2.r, c1.i + c2.i)endfunction P.sub(c1, c2)    return P.new(c1.r - c2.r, c1.i - c2.i)endfunction P.mul(c1, c2)    return P.new(c1.r*c2.r - c1.i*c2.i, c1.r*c2.i + c1.i*c2.r)endfunction P.inv(c1, c2)    local n = c.r^2 + c.i^2    return P.new(c.r/n, -c.i/n)endreturn P                        --记得返回该对象本身

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

0 0