Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Insert table to table

Tags:

lua

lua-table

Basic table, how they should be. But me need do it by function, how i can do that?

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
  }

Table should be based on outside params, and code one table for each variable of options - not better way. I make a function for that, they should create basic options like caption or description and pop up, and insert values to buttons table (if option enabled - add button). But here the problem, they wont insert to tmp table, buttons table and their values for next options.

   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 i can fixing them?

like image 973
Happy Day Avatar asked Jun 30 '13 04:06

Happy Day


1 Answers

From looking at your createMenu function, two obvious problems stick out:

  1. assigning to global tmp a new table every time createMenu is called.
  2. using the return keyword as a key in config.

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

local tmp = {}

For the second problem, you can use a lua keyword as a table key if you really want but you won't be able to use the . dot syntax to access this since Lua will parse this the wrong way. Instead, you need to change:

config.return

to

config["return"].

Edit: After reading your comment and checking the example table, it looks like only the button table is accessed by numerical index. In that case, you'll want to use table.insert only on button. If you want to create the table to have associative keys then you'll have 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 produce the mainMenu table you're describing in your question.

like image 118
greatwolf Avatar answered Sep 29 '22 08:09

greatwolf