Ivan Lendl
Ivan Lendl

Reputation: 87

Have table value execute function using key in Lua

I am trying to make a menu system in Lua using the only data structure available: tables. I have two menus: connectionmenu and mainmenu.

I want to be able to switch between the menus. For example, from mainmenu, go to connectionmenu, and then that becomes the currentmenu that is displayed.

Here is my code: Note that I am using a library called onelua for the psp to display the menu, however my question is directly related to core lua and tables.

function changemenu(menu)
    currentmenu = menu
end

connectionmenu = {"Connection Menu Title"};
mainmenu = {"Main Menu Title"}
currentmenu = connectionmenu

connectionmenu["Connection Menu"] = changemenu(mainmenu)
mainmenu["Main Menu"] = "test value"

Now how can I execute connectionmenu["Connection Menu"]'s function?

I've tried:

return [currentmenu["Connection Menu"]]

to no avail.

Upvotes: 1

Views: 134

Answers (2)

上山老人
上山老人

Reputation: 462

I don't understand your meaning.Because I can't add a comment, I will give some advice.

First, if you want add a function to menu(connectionmenu or mainmenu), you can do as upstairs.

Secondly, if you want to execut changemenu function.You need give the element the function, not a return value of the function.You can modify like this:

connectionmenu["Connection Menu"] = changemenu

And, execute the function:

return currentmenu["Connection Menu"]();

I hope it's useful for you.

Upvotes: 1

Azure Heights
Azure Heights

Reputation: 271

Well first thing you need to make your function a part of the table:

connectionmenu = {
    "Title Here",
    func = function (firstarg, secondarg)
        -- Function body here
    end
}

Then, you can run the function by calling the func method of the table:

currentmenu.func(firstarg, secondarg)

Upvotes: 1

Related Questions