Lua Insert a table into a table

The base table is how they should be. But I need to do this by function, how can I do this?

local mainMenu = { caption = "Main Window", description = "test window", buttons = { { id = 1, value = "Info" }, { id = 2, value = "Return" }, { id = 3, value = "Ok" }, { id = 4, value = "Cancel" } }, popup = true } 

A table should be based on external parameters and encode one table for each parameter variable - not the best way. I make a function for this, they must create basic parameters, such as a title or description and pop-ups, and insert values ​​into the button table (if the option is enabled, the add button). But here is the problem, they will not insert into the tmp table, the button table and their values ​​for the following parameters.

  function createMenu() tmp = {} --buttons insert if(config.info) then table.insert(tmp, {buttons = {id = 1, value = "Info"}}); elseif(config.return) then table.insert(tmp, {buttons = {id = 2, value = "Return"}}); end --table main table.insert(tmp, { caption = "Main Window", description = "test window", popup = true }) return tmp end 

How can I fix them?

+4
source share
1 answer

createMenu at your createMenu function raises two obvious problems:

  • Assigning global tmp new table each time createMenu is called.
  • using the return keyword as the key in config .

This can be a problem if you use tmp somewhere else in your code outside of the createMenu function. The obvious fix is ​​to change it to:

 local tmp = {} 

For the second problem, you can use the lua keyword as the table keyword if you really want to, but you can't use the syntax . dot to access this, as Lua will analyze it incorrectly. Instead, you need to change:

 config.return 

to

 config["return"]. 

Change After reading your comment and checking the example table, it looks like only the button table is accessed using a numerical index. In this case, you want to use table.insert only on button . If you want to create a table with associative keys, you will need to do something like this:

 function createMenu() local tmp = { --table main caption = "Main Window", description = "test window", popup = true, --button table buttons = {} } --buttons insert if config.info then table.insert(tmp.buttons, {id = 1, value = "Info"}); elseif config['return'] then table.insert(tmp.buttons, {id = 2, value = "Return"}); end return tmp end 

This will create the mainMenu table, which you describe in your question.

+4
source

Source: https://habr.com/ru/post/1488920/


All Articles