Index and value in table.concat()

idk if this is possible but i want to make table.concat() gives me the index and value from an item. Example:

local items = {
		["apple"] = 5,
		["pen"] = 3,
		["juice"] = 4,
	}
	
print(table.concat(items, ", ")) -- I want to print this: [ apple 5, pen 3, juice 4 ]

If u have any suggestion will be appreciated, sorry for bad english!

1 Like

Unfortunately table.concat only works with arrays. You’ll have to do a bit of a workaround to get the result you’re hoping for.

local items = {
	["apple"] = 5,
	["pen"] = 3,
	["juice"] = 4,
}

local function Count(tab)
	local num = 0
	for i in next, tab do
		num = num + 1
	end
	return num
end

local function ConcatTab(tab, del)
	local str = ""
	local num = Count(tab)
	local temp = 1
	for i, v in pairs(tab) do
		if temp ~= num do
			str = str .. i .. " " .. v .. del
		elseif i == #tab then
			str = str .. i .. " " .. v
		end
		temp = temp + 1
	end
	return str
end

print("[", ConcatTab(items, ", "), "]")

If you need any kinda explanation about any of this, don’t hesitate to let me know. Peace.

1 Like

Wow! This is exactly what i needed! tysm!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.