This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Cranium's profile picture

Use functions in tables

Started by Cranium, 08 January 2013 - 12:45 PM
Cranium #1
Posted 08 January 2013 - 01:45 PM
I am trying to rewrite my SmartPaste program to make a Firewolf Edition, and maybe update my original program. Unfortunately, I have run into a slight snag. I want to have my menu options carry individual functions. What I mean is when I call to buttons[2].action, I want it to use the function I specify in the table buttons. I tried using

buttons = {
{name = not logged and "Login" or "Welcome!",
color = colors.black,
BGcolor = login and colors.red or colors.lightGray,
x1 = 1,
x2 = 5,
y = 2},
{name = fWolf and "Home" or "",
color = colors.black,
BGcolor = colors.lightGray,
action = redirect("smartpaste.com/home") --tried, but it just keeps running this function.
x1 = 21,
x2 = 25,
y = 2},
{name = "New",
color = colors.black,
BGcolor = new and colors.red or colors.lightGray,
x1 = 28,
x2 = 32,
y = 2},
{name = "Download",
color = colors.black,
BGcolor = download and colors.red or colors.lightGray,
x1 = 34,
x2 = 43,
y = 2},
{name = "Help",
color = colors.black,
BGcolor = help and colors.red or colors.lightGray,
x1 = 45,
x2 = 50,
y = 2},
{name = "X",
color = colors.white,
BGcolor = colors.red,
x1 = 51,
x2 = 51,
y = 1}
}
But it would just run the function that I specify. I want it to run the function ONLY when I call back to that table index. How would I do that? I already have the rest of the code working okay, and can call to other variables.
theoriginalbit #2
Posted 08 January 2013 - 01:50 PM
well you were close. the problem is that you are giving it a function call. not a function pointer. I would suggest having functions in the program for each of the menu items that need them. then store the pointer to those functions for the menu item. for examples


local function doHome()
  redirect("smartpaste.com/home")
end

-- then in the buttons table

action = doHome

-- then when the user clicks it

buttons[2].action()


EDIT: I love how I got the opportunity to help you ;)/> :)/>
Edited on 08 January 2013 - 12:51 PM
MysticT #3
Posted 08 January 2013 - 01:58 PM
You can also define the function inside the table:

action = function() redirect("smartpaste.com/home") end
it works the same way, just saving a few lines.
I would still recommend using the method TheOriginalBIT said in some cases. If you are going to use the same function somewhere else, it's better to define it before and then assign it where needed.
Cranium #4
Posted 08 January 2013 - 07:44 PM
Oh, well thanks you guys. That really helped. Next version is going to look great on the user end, but totally shit on the code end. Meh, as long as it works.