lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 5-Aug-05, at 7:24 PM, Glenn Maynard wrote:

"declaring" is entirely different in Lua and C (the word hardly applies
to globals in Lua). That's why the comparison seems mostly meaningless.

I just can't resist a challenge.

rlake@freeb:~/src/cdecl$ cat a.c
a = 0;

seta(i) {
  a = i;
}

geta() {
  return a;
}


rlake@freeb:~/src/cdecl$ cat main.c
a = 1;

main() {
  printf("The value of a is %d\n", geta());
  a = 2;
  printf("The value of a is %d\n", geta());
  seta(3);
  printf("The value of a is %d\n", geta());
  return 0;
}

rlake@freeb:~/src/cdecl$ gcc -o main -z muldefs main.c a.c
rlake@freeb:~/src/cdecl$ ./main
The value of a is 1
The value of a is 2
The value of a is 3

-----------------------------

OK, it's different than Lua. But completely different? I think not.

Leaving aside Lua's ability to define functions inside functions, which standard C lacks altogether, a local declaration inside a Lua function differs from a variable declaration inside a C function only in that the C variable is statically-typed. The scoping is identical, aside from the fact that Lua, unlike C, implicitly declares the variables in a for statement.

Similarly, a local declaration in Lua outside of a function is essentially the same as a static declaration in a C file. Both declare file-local variables.

The similarity between Lua local declarations and C local declarations is often missed by Lua programmers wondering how to find out the "name of a variable". Like C, Lua (local) variables do not have names; they are simply mapped to storage (on the stack) and two named variables may well share the same storage location if the compiler can demonstrates that they are not co-extent. (In Lua's case, this means that their scopes are disjoint.)

Global variables in Lua are not that similar to global variables in C, mostly because you cannot create new global variables in C at runtime. However, as the above example demonstrates, they work pretty well in the same way: the compiled C file contains a string which names the variable, and it is looked up in a hash table (at least in ELF format). In Lua, the global variable is looked up at runtime in a hash table.

I did cheat a bit in the above example, of course. First, I told the linker not to complain about the fact that 'a' is defined by both main.c and a.c. Second, I deleted several useful warnings produced by gcc. In fact, C90 does forbid the use of 'a = 1;' in main.c (and the similar initialization in a.c), but it has no problems with the function definitions.