lua-users home
lua-l archive

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


Hi Coda, Ignacio, Tim,

Thanks very much for all your kind help and time!

Best Regards
Nan Xiao

On Sat, Jul 4, 2015 at 2:11 AM, Tim Hill <drtimhill@gmail.com> wrote:

On Jul 2, 2015, at 11:39 PM, Nan Xiao <xiaonan830818@gmail.com> wrote:

Hi all,

After reading "Calling Lua From a C Program", I see it's need to call "priming lua_pcall()" or
"priming lua_dofilel()" before using "lua_getglobal()" to get a function and run it successfully.
Or the program will complain "attempt to call a nil value".

But after googling and going through "Programming in Lua", I can't find what is under the
hood. Could anyone can explain why need the the magical "priming lua_pcall"?

Thanks very much in advance!

Best Regards
Nan Xiao

There is no need for this “priming” process, as others have noted. The author seems to be using this as a way to pass state from C code into Lua (via global variables), but this is pretty crude; you are better off passing arguments on the stack as I previously outlined. Of course, if the Lua code expects a global “foo” and there isn’t one, yes it will get nil when it tries to read it, but the fix there is probably not to expect a “foo” global in the first place :)

Think about the stand-alone “lua” command that you can use to run any Lua script from the command line. This utility is just a very thin wrapper that creates a Lua state (and loads the standard libraries) reads the Lua script from a file, compiles it using lua_load(), and then calls it using lua_call(). (I’m simplifying a lot here, technically it uses slightly different APIs, but the basic model is the same).

—Tim