Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a coordinate pair as a key in a Lua table

Tags:

lua

lua-table

As the title says, I'm trying to use a coordinate pair (x, y) as a key for a table. Here is what I have done so far

local test = {_props = {}}
local mt = {}
local xMax = 5
local yMax = 5

local function coord2index(x, y)
    return ((x-1) * xMax) + y
end

mt.__index = function(s, k)
    if s._props[coord2index(k[1], k[2])] ~= nil then
        return s._props[coord2index(k[1], k[2])]
    end
end

mt.__newindex = function(s, k, v)
   s._props[coord2index(k[1], k[2])] = v 
end
mt.__call = function (t, k)
    if type(k) == "table" then print "Table" end
end

setmetatable(test, mt)

test[{1,2}] = 5
print( test[{1,2}])

This is actually working as expected. What I'm really wondering if there is a way to reduce this even more, something like test[1,2] = 5 and print(test[1,1]). There is no technical need for this, it's purely for my further edification into Lua.

like image 281
Timbermar Avatar asked Feb 28 '26 15:02

Timbermar


1 Answers

I think your method is good. You can also use strings instead of numbers and do something like return x..';'..y in your coord2index function.

like image 182
Paul Kulchenko Avatar answered Mar 02 '26 15:03

Paul Kulchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!