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”
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
Lua will automatically coerce a number to a string, so you can concatenation a string to a number directly.
One interesting point is you can coerce a string to a number just as easily.
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.
You can also shadow variables by giving them the same name, but different values depending on whether they are local or global.
One thing to note that Lua calls blocks of code “chunks”, and this is what you will see in error messages.