Created
August 5, 2015 13:33
-
-
Save iglosiggio/5f8791bf2b8d03d231e5 to your computer and use it in GitHub Desktop.
Flat multidimensional tables in lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local _mt = { | |
__call = function(t, ...) | |
-- Los primeros table.dimensiones argumentos corresponden a la | |
-- ubicación en cada eje | |
local argumentos = table.pack(...) | |
local dimensiones = #t.dimensiones | |
local indice_set_value = dimensiones + 1 | |
local indice_set_nil = dimensiones + 2 | |
local indice = 0 | |
for i = 1,dimensiones do | |
indice = indice + argumentos[i] * t.tamanio[i] | |
end | |
if argumentos[indice_set_nil] or argumentos[indice_set_value] then | |
t[indice] = argumentos[indice_set_value] | |
end | |
return t[indice] | |
end | |
} | |
local create_multidimensional_table = function(dimensions) | |
local table = {dimensiones = dimensions} | |
setmetatable(table, _mt) | |
return table | |
end | |
return { | |
create_multitable = create_multidimensional_table | |
} | |
--[[ | |
Uso: | |
lib = require("multitables.lua") | |
test = lib.create_multitable {5, 5} -- A 5x5 table | |
test(1, 1) -- it's a get, returns nil | |
test(1, 1, 3) -- it's a set, sets 3, returns 3 | |
test(1, 1, nil) -- thinks it's a get, returns 3 | |
test(1, 1, nil, true) -- it's a nil_set, sets nil, returns nil | |
test(1, 1) - it's a get, returns nil | |
]]-- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment