[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua 5.1 upvalues
- From: "Robert G. Jakabosky" <bobby@...>
- Date: Fri, 8 Apr 2011 15:59:15 -0700
On Friday 08, Anthony Howe wrote:
> On 08/04/2011 21:16, Rob Hoelz whispered from the shadows...:
> > If you want C closures to share values, you could store a table as an
> > upvalue, store your values in there, and set the same table as an
> > upvalue for the closures.
>
> Ugh. One person says no. Another suggests the very thing I want to try
> that prompted the question.
>
> In 5.1 does...
>
> lua_newtable(L);
> lua_pushvalue(L, -1);
> lua_pushcclosure(L, &foobar, 1);
> lua_pushcclosure(L, &barblat, 1);
That code should be:
lua_newtable(L);
lua_pushvalue(L, -1);
lua_pushcclosure(L, &foobar, 1);
lua_pushvalue(L, -2);
lua_pushcclosure(L, &barblat, 1);
lua_remove(L, -3);
>
> -- rinse & repeat
>
> Work? Can more than one C function share a single upvalue? I ask because
> something along these lines has been mentioned in Lua 5.2 as an
> alternative to environments or some such without any examples. So I'm
> unclear as to whether this is possible in 5.1 and/or 5.2.
Like others have said they can shared the same value, but not the same 'local'
storage of that value. As long as you don't try to store a new value in the
upvalue of one C closure and expect the other C closure to see the new value.
Lua closures can share the same 'local' storage for an upvalue:
local shared_storage = 123
function foobar(new_val)
shared_storage = new_val -- changes the shared value
end
function barblat()
return shared_storage -- will see changes from foobar()
end
print(barblat()) -- 123
foobar(456)
print(barblat()) -- 456
--
Robert G. Jakabosky