Loading multiple LUA tables as data

Started by
3 comments, last by GutenTag 8 years, 7 months ago

Hey everyone, I've spent the past 4 hours hammering away at this problem to no avail (Either I'm really bad at understanding the lua stack, or it's something else entirely)

Suppose I have an lua file structured like this


ID1 = {

    name = "Description 1",

    mod = 20

},



ID2 = {

    name = "Description 2",

    mod = -15

}

And now suppose I need to get this loaded into a structure I have.

And my question is, how do I do it? How can I iterate though all these tables dynamically and load these values in. I've tried using lua_next and other methods, but all they do is spit out access violation reading exceptions.

Edit: Whoops, wrong subforum. Could I have this moved to API?

Advertisement

Create a read function, then enclose your data with the read which handles the data.

Example main.lua


my_data_container = {}

read = function( _chunk)
  -- get id
  local id = _chunk.id
  -- assign table to container
  my_data_container[id] = _chunk

.. do some processing..
end


do_file("my_data_file.lua")


You data should look like this


read({
    id = "ID1",
    name = "Description 1",
    mod = 20
})



read({
    id = "ID2",
    name = "Description 2",
    mod = -15
})

When calling a function with just a table you can leave the parentheses away:


read{
    id = "ID1",
    name = "Description 1",
    mod = 20
}



read{
    id = "ID2",
    name = "Description 2",
    mod = -15
}

Alternative for full-data table without the need of any processing just setup your data like this:


my_data_container = 
{
  ID1 =
  {
    name = "Description 1",
    mod = 20
  },
  ID2 = 
  {
    name = "Description 2",
    mod = -15
  },
}

This is actually much better than what I had, thank you!

Edit: Small question, If I follow that last suggestion, how do I access the tables contained within "my_data_container"

(Sorry, lua just seems very needlessly obscure about what I need to do to access items in the stack)


Edit: Small question, If I follow that last suggestion, how do I access the tables contained within "my_data_container"

If you just declare a variable in a file using dofile, it is automatically global. Therefor you can handle it like any other global variable


local item = my_data_container.ID1
local item2 = my_data_container["ID1"]


Edit: Small question, If I follow that last suggestion, how do I access the tables contained within "my_data_container"

If you just declare a variable in a file using dofile, it is automatically global. Therefor you can handle it like any other global variable


local item = my_data_container.ID1
local item2 = my_data_container["ID1"]

Thanks!

I also finally managed to get it to work after enough fiddling with the stack and more review of the reference manual.

This topic is closed to new replies.

Advertisement