lua-users home
lua-l archive

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


A.lua:
return function‎(init)
   local num=init
   return {print_num=function() print(num)}
end

‎B.lua:
local A=require("A")(100)


From: 俞江
Sent: samedi 19 juillet 2014 18:05
To: Lua mailing list
Reply To: Lua mailing list
Subject: Re: How to change a module's upvalue?

Oh, I just cut it from my code so ... sorry for my mistake.

local num = 1
function print_num()
    print(num)
end
return {print_num = print_num}

and Used as:

A = require('a')
A.print_num()


2014-07-19 22:53 GMT+08:00 Rena <hyperhacker@gmail.com>:
On Sat, Jul 19, 2014 at 10:46 AM, 俞江 <devyujiang@gmail.com> wrote:
>
> Hi all!
>     There is a module 'a.lua':
>
> local num = 1
> function print_num()
>     print(num)
> end
>
>      And used as:
> A = require('a')
>
>     I want to change the 'num' to 10 in the runtime, but
> load("local num=100",nil,nil,A)()
> load("num=100",nil,nil,A)()
>     does not work, how to do it?
>
>
>
>
>

I'm not sure what you're trying to do with load(). It looks like
you've given A as the environment rather than the function. Also,
since the module doesn't return anything, require('a') will return
true. (and will set the global print_num, which may or may not be your
intention; it's considered bad practice for modules to set globals.)

There is debug.setupvalue() to change upvalues of a function. However,
it takes an upvalue index, not a name, so you'd need to loop through
the function's upvalues with debug.getupvalue(), find the one named
'num', and change it. (I'm not sure if upvalue indexes start at 0 or
1, though.)




--
Sent from my Game Boy.