I'm still pretty new to Lua, and I'm trying to wrap my head around best practices. I have a chunk of code that will occasionally index a 2D table with out-of-bounds values. If the 1st index is invalid, it crashes (fair enough since nil can't do anything with the 2nd index). I want the code to find the proper values for proper indices, and return nil for everything else. I'll add a bunch of error-checking if I need to, but that doesn't seem terribly elegant. I'm thinking metatables might be the answer here, but I'm not sure if this is considered best practice or not.
Here's my (functional!) reduced code:
Code: Select all
-- The goal is to be able to lookup ANY 2D index without tripping over an error
map = {w=10, h=10}
for x = 1, map.w do
map[x] = {}
for y = 1, map.h do
map[x][y] = love.math.random()
end
end
setmetatable(map, { __call = function(t, x, y) return x>0 and x<=t.w and y>0 and y<=t.h and t[x][y] or nil end })
print(map[2][5])
print(map[7][21])
--~ print(map[21][7]) -- THIS CRASHES
print(map(2,5))
print(map(7,21))
print(map(21,7))
Is this best practice? Why or why not? Is there any way to make it work with out-of-bounds [] references, or is __call() the only way to go? I don't really have a handle on metatables, by the way. I've been reading about them for days now, and I've just spent the last 2 hours getting this chunk of code to work.
Any code samples/ideas by me should be considered Public Domain (no attribution needed) license unless otherwise stated.