String & Scope Basics
01/12/21 14:59 Filed in: Lua
This time around I take a quick look at the basics of Lua strings and how scope works.
Strings
Lua lets you get the length of a string (a very common and useful activity) two different ways.
string.len(“hello world")
#”hello world”
![3340B21E-6E8B-4F9A-9DB6-B3A8E72799A8_4_5005_c](3340b21e-6e8b-4f9a-9db6-b3a8e72799a8_4_5005_c.jpeg)
The # (it’s not a hash-mark, it’s an octothorp) looks a bit weird prepending a string, but I can get used to it.
Concatenation two strings also uses a strange syntax.
string1..string2
![30356919-4C9A-4B22-A529-B4529859F1E3_4_5005_c](30356919-4c9a-4b22-a529-b4529859f1e3_4_5005_c.jpeg)
![F61CA1FC-5A8C-4E35-A99A-5295FE17D7D9_4_5005_c](f61ca1fc-5a8c-4e35-a99a-5295fe17d7d9_4_5005_c.jpeg)
Lua will automatically coerce a number to a string, so you can concatenation a string to a number directly.
![7C4B9D83-14A9-44F8-98FD-803F75B80E38_4_5005_c](7c4b9d83-14a9-44f8-98fd-803f75b80e38_4_5005_c.jpeg)
One interesting point is you can coerce a string to a number just as easily.
![9B00DFEA-0245-42D8-9373-A597D87DD538_4_5005_c](9b00dfea-0245-42d8-9373-a597d87dd538_4_5005_c.jpeg)
Scope
Lua has the concept of scope as do most languages. Scope is organized around blocks of code. A block of code can hold other blocks of code.
A file is a block of code.
Blocks of code within a file are designated by:
do
— local block
end
This is similar to the COBOL
BEGIN
END.
A block of code can access any data it contains, but not the data outside of itself.
You can also use the keyword local to make a variable local, otherwise it is global by default. Variables need to be explicitly marked as local.
![8C16EC1B-A069-4BE5-A71F-F991B2CCA512_1_201_a](8c16ec1b-a069-4be5-a71f-f991b2cca512_1_201_a.jpeg)
You can also shadow variables by giving them the same name, but different values depending on whether they are local or global.
![76D49D57-5B13-4FE9-9982-1B5242746FBA_1_201_a](76d49d57-5b13-4fe9-9982-1b5242746fba_1_201_a.jpeg)
One thing to note that Lua calls blocks of code “chunks”, and this is what you will see in error messages.