Can somebody help me about the string?

Posted by Doghell on Fri 28 Aug 2009 07:36 AM — 3 posts, 12,792 views.

#0
hello everyone:
i am a beginner of lua. last day i've read a article which mentions that "First, all strings in Lua are internalized;
this means that Lua keeps a single copy of any string. Whenever a new string
appears, Lua checks whether it already has a copy of that string and, if so,
reuses that copy."
[http://www.lua.org/gems/](here is the book).
So yep i just wanna know if i define like this:
>s1 = "hello"
>s2 = "hello"
do s1 and s2 use the same copy? I try to see the address of the two string in the memory, but i don't know how to do it?
(i don't speak english, so excuse me for my poor english,:))
thank you everybody!
Amended on Fri 28 Aug 2009 07:37 AM by Doghell
Australia Forum Administrator #1
Why do you want to see the addresses? This is an internal thing that you don't need to know in a scripting language.

However I believe that s1 and s2 in your example will refer to the same string.

This make string assignment fast, eg.


s1 = "some very large string"

s2 = s1    -- copy very quickly, as it takes a copy of the pointer to the string


In your case, if you compare s1 and s2 they will compare equal. ie.


s1 = "hello"
s2 = "hello"

print (s1 == s2)  -- true


You can also assign functions, eg.


f1 = function () print "hi there" end
f2 = f1

f2 ()  -- prints: "hi there"

#2
Nick Gammon said:

Why do you want to see the addresses? This is an internal thing that you don't need to know in a scripting language.

However I believe that s1 and s2 in your example will refer to the same string.

This make string assignment fast, eg.


s1 = "some very large string"

s2 = s1    -- copy very quickly, as it takes a copy of the pointer to the string


In your case, if you compare s1 and s2 they will compare equal. ie.


s1 = "hello"
s2 = "hello"

print (s1 == s2)  -- true


You can also assign functions, eg.


f1 = function () print "hi there" end
f2 = f1

f2 ()  -- prints: "hi there"



Year,thank you very much,Nick.I just wanna test that if these two strings refer to the same string(this is why I'd like to see their addresses).When I define two tables,

t1 = {1,2,3} -- this is a table
t2 = {1,2,3} -- and this is another table

they are two different tables.
Just now I have read some words that prove you are right.
"For strings reuse is not necessary, because Lua
does the job for us: it always internalizes all strings it uses, therefore reusing
them whenever possible. For tables, however, reuse may be quite effective."
And thank you again! :)