Search code examples
javascriptluagetter

Converting a Javascript Object to Lua table


I have a Javascript object where one of the keys is a getter and I want to convert the entire object to a Lua table in order to use it in a wiki module. So far I have managed to find how to convert all key,value pairs except the getter. I can't find any way to proceed.

The JS object is the following:

var obj = {
    'acad': {
            mL:50,
            w:[64,68,115,263,382,626],
            g:[0,0,0,0,225,428,744],
            mS:[0,8,12,16,22,28,35],
            tm:{a:1440,b:1,c:1.2,d:720,e:[984]},
            get d(){var t=[],c=this.tm;for(var i=0;i<this.mL;i++){var d=Math.round(c.a/c.b*Math.pow(c.c,i+1)-c.d)-(c.e!=undefined?(c.e[i]!=undefined?c.e[i]:0):0);t.push((d>1728e3?1728e3:d));}return t;}
        }
}

and the Lua table so far is:

local obj = {
    ["acad"] = {
            ["mL"] = 50,
            ["w"] = {64,68,115,263,382,626},
            ["g"] = {0,0,0,0,225,428,744},
            ["mS"] = {0,8,12,16,22,28,35},
            ["tm"] = {
                    ["a"] = 1440,
                    ["b"] = 1,
                    ["c"] = 1.2,
                    ["d"] = 720,
                    ["e"] = {984}
                },
            get d(){var t=[],c=this.tm;for(var i=0;i<this.mL;i++){var d=Math.round(c.a/c.b*Math.pow(c.c,i+1)-c.d)-(c.e!=undefined?(c.e[i]!=undefined?c.e[i]:0):0);t.push((d>1728e3?1728e3:d));}return t;}
        }
}

Any ideas?


Solution

  • JS-like getter properties in Lua are possible (using metatables), but function members are preferred:

    local obj = {
        acad = {
            mL = 50,
            w = {64,68,115,263,382,626},
            g = {0,0,0,0,225,428,744},
            mS = {0,8,12,16,22,28,35},
            tm = {a=1440, b=1, c=1.2, d=720, e={984}},
            d = function(self)
                    local t, tm = {}, self.tm
                    for i = 1, self.mL do 
                        local d = math.floor(tm.a / tm.b * tm.c ^ i - tm.d + .5) - (tm.e and tm.e[i] or 0)
                        table.insert(t, math.min(d, 1728000))
                    end
                    return t
                end
        }
    }
    
    -- How to get array "d":
    local d = obj.acad:d()