String & Scope Basics

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

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

F61CA1FC-5A8C-4E35-A99A-5295FE17D7D9_4_5005_c


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

One interesting point is you can coerce a string to a number just as easily.

9B00DFEA-0245-42D8-9373-A597D87DD538_4_5005_c

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

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

One thing to note that Lua calls blocks of code “chunks”, and this is what you will see in error messages.

This site does not track your information.