Why does this happen in Lua?

I’m trying to yield a thread that inside a table but upon trying to define the thread it is declared unknown…
Why does that happen?

local __TOUCHBURN = coroutine.create(function()
	for _,v in Character:GetChildren() do
		if v:IsA("BasePart") then
			if __CHARSTATS:WaitForChild("__BURNING").Value == true then
				v.Touched:Connect(function(__PART)
					--
				end)
			else
				coroutine.yield(__TOUCHBURN) -- Thread is unknown according to lua
			end
		end
	end
end)

Not sure if you can yield a coroutine inside itself, but I don’t know much about coroutines themselves.

It’s because at the point of time where the function is created, there is no reference to a local variable __TOUCHBURN (not even nil). It’s an awkward quirk with no good solution that I’m aware of other than forward declaring or using a global instead (omit local).

-- forward declaration
local __TOUCHBURN
__TOUCHBURN = coroutine.create(function()

The more classic example is with event connections, where it will outright error.

local bindable = Instance.new("BindableEvent")

local conn = bindable.Event:Connect(function()
	print("Running")
	conn:Disconnect() -- attempt to index nil with 'Disconnect'
	print("Finished")
end)

bindable:Fire()

The same thing can happen with function definitions, if you use the pure method. You should notice the similarities between that at the broken code.

-- Pure function definition
local a = function(exit)
	print("Recursive", exit)
	if not exit then
		a(true) -- unknown global 'a'
	end
end

-- Syntactic sugar function definition
function b(exit)
	print("Recursive", exit)
	if not exit then
		b(true)
	end
end

-- Syntactic sugar equivalent
local b
b = function(exit)
	print("Recursive", exit)
	if not exit then
		b(true)
	end
end

You can read the actual documentation about this stuff here.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.