Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

global table returns as nil?

I'm trying to create a global table for dev notes. whenever I try to get info from _G.updates it always returns nil. So output for this script is the version text, but then it prints a 0

Why is this happening?

_G.version = "0.7.3"

_G.updates = {
	update_1 = {
		version = "version 0.7.1",
		date = "7/10/16-8/10/16",
		texts = {"-front door swings open & doesn't look like crap",
				"-added moving doors w/ buttons to mains generator",
				"-secret vent door swings open",
				"-added ice environment around facility",
				"-started work on game environment lighting engine (optimized & more poweful power functions)",
				"-added dynamic lighting for A1"
				}
	},
	
	update_2 = {
		version = "version 0.7.2",
		date = "8/12/16",
		texts = {"-added blizzard type effect on surface",
				"-re-scripted 'snowed in' function, aminated & longer"
				}		
	},
	
	update_3 = {
		version = "version 0.7.3",
		date = "8/15/16",
		texts = {"-added sound engine for ambient noises",
				"-added wind sound if you are outside on the surface"
				}			
	}
}

print("version = " .. _G.version)
print(#(_G.updates))

5 comments

2

This is because you're trying to get the length of a dictionary. You can only get the length of a table written as an array. More: https://scriptinghelpers.org/questions/28182/how-to-learn-tables#31632

2

I'd like to add, you can't get the length of a dictionary with the "#" operator. There are other ways of getting the length of a dictionary, however.

0

Thank you for the thorough post. How would I go about iterating thru a dictionary?

0

You would have to use a generic 'for' loop with the 'pairs' function.

0

@link yeah that's one way. i actually had to just convert my dictionary into a table because i wanted to iterate reverse thru the whole thing

1 answer

Try iterating through the table like so:

local len = 0 -- gets how many updates there are
for _,v in pairs (_G.updates) do -- iterates through the table
	len = len + 1
end

local currentVersion = _G.updates["update_"..len].version -- the latest version

for i = 1,len do -- iterates through all the updates
	local curValue = _G.updates["update_"..i] -- the update currently being 'selected' by the for loop
	-- do stuff here
end

If you wanted to iterate backwards:

for i = len,1,-1 do
	local curValue = _G.updates["update_"..i]
end

I believe that when you index a value in a table using tab.value1, it can also be indexed using tab["value1"]. This means thats I can use string manipulation to find values in a table.


Hope I helped!

~TDP

This discussion is preserved as it was. New answers, comments, and votes are closed.