lua-users home
lua-l archive

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


> Ok and what I wanted to do is to take that loaded (not started) program, use
> lua_getglobal() to look for a function called START and if it's found then
> call it (but don't call the anonymous function around it). But that doesn't
> seem to be possible because for some strange reason lua_loadstring() doesn't
> care about putting the symbol START onto the global index table.

"Putting symbols" into the global index table -- or any activity
whatsoever in Lua (from Lua side, not C) is not possible without
calling a function.

There are no special mechanisms in Lua for setting globals before code
chunk is run.

Note that

function START() end

is a syntax sugar, and for the matter of our discussion is equivalent to

START = function() end

Which is the same as if you written START = 42, only after it is
executed global variable START would contain not number 42, but a
function. (Functions are the first class values in Lua.)

You may see it in the bytecode dump:

$ luac -l -
START = 42
^D
# This is the anonymous function of the main chunk
main <stdin:0,0> (3 instructions, 12 bytes at 0x100b30)
0+ params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions
# Load constant 42
	1	[1]	LOADK    	0 -2	; 42
# Assign it to the global variable START
	2	[1]	SETGLOBAL	0 -1	; START
	3	[1]	RETURN   	0 1

Note how it is similar to our case:

$ luac -l -
function START() print("test") end
^D
# This is the anonymous function of the main chunk
main <stdin:0,0> (3 instructions, 12 bytes at 0x100b30)
0+ params, 2 slots, 0 upvalues, 0 locals, 1 constant, 1 function
# This is where "body" of a  function START is defined (see below)
	1	[1]	CLOSURE  	0 0	; 0x100490
# This is where body of a function START is assigned to the global variable
	2	[1]	SETGLOBAL	0 -1	; START
	3	[1]	RETURN   	0 1

# This is the body of a function START itself
function <stdin:1,1> (4 instructions, 16 bytes at 0x100490)
0 params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions
	1	[1]	GETGLOBAL	0 -1	; print
	2	[1]	LOADK    	1 -2	; "test"
	3	[1]	CALL     	0 2 1
	4	[1]	RETURN   	0 1

> I don't see how I've a misunderstanding of loading and running a program.
> Rather I seem to have a misunderstanding about  how/when global symbols are
> registered into the global index table. Couldn't find anything in the docs
> about that.

As you can see, it is that anonymous function lua_loadstring() is that
"mechanism" that puts START into the global table.

If your code comes from a trusted source, you'll do no harm calling
this function.

If not -- you'll need full-scale sandboxing anyway.

BTW, it is not necessary to use a global variable to hold a function
in your case. You may return the function from the chunk:

return function()
 print("test")
end

(And handle it as you'd handle any return value from lua_pcall().)

This is arguably cleaner.

HTH,
Alexander.