lua-users home
lua-l archive

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


Thanks Rena

 

Rick

From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On Behalf Of Rena
Sent: Wednesday, August 17, 2016 2:23 PM
To: Lua Mailing List
Subject: Re: Passing Arguments to a Lua Script

 

On Aug 17, 2016 4:37 PM, "Leinen, Rick" <RLeinen@leviton.com> wrote:
>
> Thanks for the help you have given me in the past.
>
>  
>
> I have what I assume will be an easy question to answer.
>
>  
>
> I have successfully been able to call a Lua function with arguments defined within a Lua script from C.  I am wondering whether you can pass arguments from C when you call the script.  If so, how do I assign the arguments to variables within the script?
>
>  
>
> Thanks,
>
>  
>
> Rick
>
>  
>
>  
>
>  

Whatever method you use to load the script should leave a function on the stack, which you call using lua_call or similar. As described in the manual for those methods, to pass arguments to the function, you push them to the stack (after the function is already there), and tell lua_call how many arguments you pushed.

The called script receives the arguments via the ... operator:

C:
luaL_loadstring(L, "your Lua code here");
lua_pushinteger(L, 2);
lua_pushinteger(L, 5);
lua_pushinteger(L, 8);
lua_call(L, 3, 0); //3 args, 0 return values

Lua:
local x, y, z = ...
assert(x == 2)
assert(y == 5)
assert(z == 8)

(if fewer than 3 arguments were passed -  even zero - the remaining items are set to nil. If more than 3 are passed, the extras are discarded. Use select('#', ...) to check how many arguments were passed.)