While we're at it, I'd like to understand the use of "local" variables a little better. I understand that their scope is within the block they're contained in. But shouldn't we be using local variables whenever possible?
And what's the meaning of a local variable defined at the beginning of the "main" block? Is that permitted?
There's nothing special about the "main" block, so yes, locals are fine at file scope. They are just local to that chunk.
Using locals everywhere is generally fine and can efficient, but there are some subtleties that can trip you up. If you use a local before it is defined, you will get the global instead.
You might expect something like
function foo()
return x+1
end
local x = 1
foo()
to be fine, but it will cause an error, because when foo() is created, it x is bound to the global named x. If X isn't local, it will return 2, because the value is assigned before foo is executed.
If you move local x = 1 to before foo, that will also work because x inside foo is bound to the local x.
The real power of using locals defined at a higher scope than the function is closures, but that's a topic for another post.
I read that local variables are accessed with an index address, while global variables use a hash table? Can you explain this? Would this mean that local variables take less memory and are accessed faster? Is the text name of a global variable stored, so longer names take more memory?
Globals are stored in a regular lua table, which by default is available as a global named _G. (and yes. _G._G = _G) They are somewhat less efficient than locals, but this likely doesn't matter in most cases. You can also create "environments" so different parts of the code have different global tables, see
http://www.lua.org/manual/5.1/manual.html#2.9The fun thing about globals being in a table is that you can attach metamethods to it just like any other table. One of the "warts" of lua is that undeclared globals are just a nil value, so if you mistype a variable name, it can go unnoticed. You can use metamethods to change this, so globals have to be declared to be used.
I was thinking about writing a program in Lua to run on the computer, not the camera. How hard is it to create a complete file that runs a Lua program on Windows or Mac, i.e. would the Lua program be cross platform?
If you use the standard command line interface to Lua (the "lua" command included with any standard lua distribution), then it should be very portable.
The lua library itself is also very portable, so if you embed it in an ANSI C program, it should run anywhere with an ANSI compiler and standard libraries.
I tend to use
chdkptp as a place to run quick and dirty lua code, even when it's not directly related to the ptp part. (see extras/vxromlog.lua for an example)
the chdk tools directory also contains "hostlua" which is set up to allow you to build a version of lua more similar to what runs on CHDK.