I’m a novice Lua programmer, and I just didn’t really like the table.insert(…) so I made this code. I don’t know if it was already possible to do something like this. However, I thought I’d share it and would love feedback from more experienced Lua programmers.
function setup()
MenuList = PythonMethod({})
ButtonList = PythonMethod({})
MenuList:insert( Menu("MainMenu", color(255,255,255)) ) --Create a MainMenu
MenuList:insert( Menu("Screen2", color(0, 0, 0)) ) --Create a second screen
ButtonList:insert( Button("Go to Screen 2", WIDTH/2, HEIGHT/2, function() func=MenuList["tab"][2] end))
func=MenuList["tab"][1]
end
function draw()
func:draw()
for ButtonPos,Button in pairs(ButtonList["tab"]) do Button:draw() end
end
function touched(t)
for ButtonPos, Button in pairs(ButtonList["tab"]) do Button:touched(t) end
end
Menu = class()
function Menu:init(name,bg)
self.bg = bg
self.name = name
end
function Menu:draw()
background(self.bg)
end
Button = class()
function Button:init(name,x,y,op)
self.x = x
self.y = y
self.w, self.h = textSize(name)
self.name = name
self.sel=false
self.onpressed = op
end
function Button:draw()
rectMode(CENTER)
if self.sel then fill(11, 255, 0, 255) else fill(127, 127, 127) end
rect(self.x, self.y, self.w+40, self.h+10)
fill(255, 255, 255, 255)
text(self.name, self.x, self.y)
end
function Button:touched(t)
if t.x > self.x-20 and t.x < self.x+20 and t.y > self.y - 20 and t.y < self.y + 20 then
if t.state == MOVING then
self.sel = true
elseif t.state == ENDED then
self.onpressed()
self.sel = false
end
else
self.sel = false
end
end
I have Python Method as a dependency
PythonMethod = class()
function PythonMethod:init(t) -- initialize the table
self.tab=t
end
function PythonMethod:concat(...) -- Perform concat
table.concat(self.tab, ...)
end
function PythonMethod:move(...)
print(type(t))
end
function PythonMethod:insert(...) -- add another entry to the table
table.insert(self.tab, ...)
end
function PythonMethod:remove(pos) --Removes element or table if nil
if pos ~= nil then
table.remove(self.tab, pos)
else
self.tab = nil
end
end
function PythonMethod:sort(...) -- Sort the table
table.sort(self.tab, ...)
end
function PythonMethod:print(pos) -- print each table entry if not defined
if pos == nil then
for a,b in pairs(self.tab) do
print(a,b)
end
else
print(self.tab[pos])
end
end