I've got a Lua script that presents an interactive text menu for configuring the script before actually doing the work. There is a main_menu()
function, which has options the user can select, each of which call a different submenu()
function. Each of those different submenu()
functions do their thing and then they go back to (they call) the main_menu()
function. Finally, each function has a parameter of settings
passed to it, which is a table of settings.
Things look like this:
local function submenu(settings)
-- Get user input & change a settings{} table key accordingly
main_menu(settings)
end
local function main_menu(settings)
-- Present choices & get user input
submenu(settings)
end
local settings={}
settings["foo"] = "bar"
main_menu(settings)
The problem is I'm getting attempt to call nil
errors whenever (as far as I can tell) a function calls another function that is defined later on in the script. So if, as in the example above, I define submenu()
and then main_menu()
, main_menu()
has no problem calling submenu()
, but submenu()
can't call main_menu()
.
FWIW, this is being done in the ComputerCraft mod for Minecraft.
You could either do a local function
with forward declaration like this:
local main_menu
local function submenu(settings)
-- Get user input & change a settings{} table key accordingly
main_menu(settings)
end
main_menu = function(settings)
-- Present choices & get user input
submenu(settings)
end
or do a global function declaration by removing local
keywords:
function submenu(settings)
-- Get user input & change a settings{} table key accordingly
main_menu(settings)
end
function main_menu(settings)
-- Present choices & get user input
submenu(settings)
end