Tables within tables (Lua)

I have some data formatted thus:

M.data = {
	{
		{a = 1, b = 2, c = 3},
		{a = 1, b = 2, c = 3},
		{a = 1, b = 2, c = 3},
		{a = 1, b = 2, c = 3},

	},
	{
		{a = 1, b = 2, c = 3},
		{a = 1, b = 2, c = 3},
		{a = 1, b = 2, c = 3},
		{a = 1, b = 2, c = 3},
	}
}

I want to define the innermost table once rather than writing it out 8 times like this. If I define a separate table with the a,b,c definitions and include that, it’s passed as a reference so all 8 are pointing to the same data, which is no good. Is this possible with Lua?

You want to use a deep copy yes?

Yes, I want a separate table created for each of the 8 entries. Basically a 2D array of structs in C/C++.

Try one of these? There are various other versions you could try too.

Thanks, I’ll probably go with the first example. Was hoping it could be all done in the definition but I guess Lua doesn’t quite allow it.

It might be possible with meta tables still.

How would you ideally like to define it? What’s your goal? Do you want to reduce time typing, reduce lines of code, improve ease of modification, or something else? The normal way to define them each explicitly as different tables in lua is the way you are doing it now, of course. You could use a function that returns a table like that instead, or if each entry is identical, to generate the whole thing.

Click to show code
local dataEntryCount = 100

M.data = {}

local function innermost()
	return {a = 1, b = 2, c = 3}
end

local function inner()
	local t = {}
	for i=1,4 do
		t[i] = innermost()
	end
	return t
end

for i=1,dataEntryCount do
	M.data[i] = inner()
end

In one of my projects, we have a little function to add or modify values in a table.

Click to show code
function mod(obj, props)
	for name,prop in pairs(props) do
		obj[name] = prop
	end
	return obj
end

It’s nice if you have fairly large identical tables (or ‘objects’) and want to modify a few different values in each.

Click to show code
local function Object()
	return {a = 1, b = 2, c = 3}
end

local obj1 = mod(Object(), {b = 5})
local obj2 = mod(Object(), {extra = "hello"})
6 Likes

Coming from a C/C++ background where you have structures, I was attempting to do something similar with Lua without resorting to using code. I think in reality, it’s easiest to have a function that creates the tables I need rather than trying to get creative with definitions.

2 Likes