lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>> So I think my problem is, that I have to index the table with the same string object as before, not just with the same string.<<

The text you quoted is not related to your problem. It is perfectly valid to do the following:

t = {a = "just some text"}
print(t["a"])
print(t["a"])	-- different "a" string but accesses the same value
print(t.a)		-- alternative syntax / syntactic sugar


You can also write your function like this:

function foo()
	if not t.a then t.a = {} end
	if not t.a.b then t.a.b = {} end
	...
	-- ... but t.a.b.2.5 won't work, in that case you have to write t.a.b.["2.5"]
end

I assume your problem is the second function call. Maybe you have closed the Lua state between calls, or another function assigns t = nil? If you could post the error message you are getting we might be able to help you more.

-----Ursprüngliche Nachricht-----
Von: lua-bounces@bazar2.conectiva.com.br [mailto:lua-bounces@bazar2.conectiva.com.br] Im Auftrag von Eva Schmidt
Gesendet: Dienstag, 5. Juni 2007 11:21
An: Lua list
Betreff: Strings as Keys in table

Hello,

I've got some problems with table indexing with strings in Lua:

I have a table with tables inside indexed like that

-- global 	
t = {}

function foo()
...
	if  not t["a"]  then  t["a"] = {} end
	if not t["a"]["b"] then t["a"]["b"] = {} end
	...
	if not t["a"]["b"][..]["2.5"] then t["a"]["b"][..]["2.5"] = 20 end ...
end

My problem now is that even if the table index exists already it is not found if the function is called for the second time - so every time the function is called the table will be newly created.

The Lua Wiki told me :

"
Strings as references

Aside: The fact that keys are references, and strings can be used, tells us something about Lua's internals. We must be referring to the same string when we get and set the value or table string keys wouldn't work! Strings are not duplicated in Lua internally, so when you reference a string with the same value you are referring to the same string.
"

So I think my problem is, that I have to index the table with the same string object as before, not just with the same string.

Does anybody have an idea how to realize that as smart as possible? Maybe some kind of a hash table ...?

Thanks for any help!

Cheers, Eva