lua-users home
lua-l archive

global & unique

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


Following solution is expensive.
Perhaps, you will advise the best?
Thanks in advance.
---[inc.lua]---
print(s)
---
---[main.lua]---
-- Global (but unique for thread) variables?
setmetatable(_G,
 {__index = function(t, k) return getfenv(0)[k] end})
local function include(file)
	local fun = _LOADED[file]
	if not fun then
		fun = assert(loadfile(file))
		setfenv(fun, _G)
		_LOADED[file] = fun
	end
	return fun()
end
local function th(a)
	local env = setmetatable({s = a}, {__index = _G})
	setfenv(0, env)
	include"inc.lua"
	coroutine.yield()
	include"inc.lua"
end
local co1, co2 = coroutine.create(th), coroutine.create(th)
coroutine.resume(co1, 1)
coroutine.resume(co2, 2)
coroutine.resume(co1)
coroutine.resume(co2)
---
Prints:
1
2
1
2

AltStyle によって変換されたページ (->オリジナル) /