lua-users home
lua-l archive

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


The code is write by Lua:

function factory()
local i = 0
local a = function()
i = i + 1
print(i)
end
local b = function()
i = i * 2
print(i)
end
return a,b
end

a,b = factory()
a() --1
b() --2

Like this,a and b can transmit data by upvalues.But I don't know how to
write the factory function by C language.Like the example:

int a(lua_State *L){
double val = lua_tonumber(L,lua_upvalueindex(1));
lua_pushnumber(L,val + 1);
lua_replace(L,lua_upvalueindex(1));
printf("%f\n",val + 1);
return 0;
}
int b(lua_State *L){
double val = lua_tonumber(L,lua_upvalueindex(1));
lua_pushnumber(L,val * 2);
lua_replace(L,lua_upvalueindex(1));
printf("%f\n",val * 2);
return 0;
}
int factory(lua_State *L){
lua_pushnumber(L,0);
lua_pushcclosure(L,a,1);
lua_pushnumber(L,0);
lua_pushcclosure(L,b,1);
return 2;
}

The return value of two closures are different upvalues,if you register
factory in Lua,then write these code:
a,b = factory()
a() --1
b() --0