How can I call a function without defining it first?

I want to do somthing like this

doThis()

function doThis()
   print("hello world")
end

Why though. Just define it before. It doesn’t make sense for Lua(u) to call something that doesn’t exist yet.

I want to put all my functions at the bottom

--Main loop 
while true do
     print()
end

function print()
     print("yes")
end
1 Like

You’ll have to define them before. And since the loop is non-terminating, Lua(u) wouldn’t even get to defining the function in the first place.

1 Like

Functions should always go at the top of the script, just below constants/variables.

Functions use the variable environment at time of calling, not time of definition.

function foo()
  print(bar)
end

local bar = "hello"
foo() --> hello
2 Likes

Luau or any most programming languages for that matter can’t use something that doesn’t exist.

is it possible to do something like this in lua
image

But there are quite a few languages that initialize all functions before running anything.

2 Likes

Forward declaration? Yes, but it won’t have the same effect.

local meow()

function main()
    meow()
end
-- calling `main` here will error

function meow()
    print("meow")
end

-- calling `main` here will work.

But in this case that is unnecessary. The variable will exist whenever you call main, but if you call main before the meow at the bottom of the script, it will error since meow will still be nil. To my knowledge this is also true in C, but I’m likely wrong.

2 Likes

Hey, I have been looking for the solution for this issue too, but couldn’t find really anything helpful, but I managed to predefine it. If anyone is also looking how to do it, here is how I did it:

local meow = function() end
local main = function()
	for i=0,3,1 do
		meow()
	end
end
meow = function()
	print("meow")
end
main()

Sadly we can’t do like local function meow() as we already defined the function, so at least there is a way.


local table = {}

table.foo()

function table.foo()

end

???

1 Like