NiklausTseng
NiklausTseng

Reputation: 235

What's the type of the anonymous function in Lua?

In Lua reference manual, it says that every value has a type which might be one of the local, global, table field types. My question is what's the type of the anonymous function in Lua? What life cycle the anonymous function has? I just show an example.

local co = coroutine.create( function () print "hi" end )

print(coroutine.status(co))

Upvotes: 2

Views: 1032

Answers (3)

Tom Blodget
Tom Blodget

Reputation: 20812

You are confusing values and variables. Values have data types like string, table, function, etc. Call the type function on an expression to get its type.

Variables refer to values but don't have a data type. The categories you are referring to: global, local and table field are not data types.

The concepts are orthogonal. For example: A local value can be of any data type; A function can be referred to by a global, local or table field.

As explained elsewhere (manual and comments), all function values are anonymous so that is not a separate category.

The lifetime of a value is always from the time it was first evaluated until no variable references it.

Upvotes: 1

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

I think there is some mix of concepts here. As others already said, Lua only has anonymous functions, which have type function (type(function() end) == 'function'). These anonymous functions can be assigned to variables, which can then be used to call functions; these are conveniently used as "names" for functions, but they are really names for variables that store values of type "function".

In terms of their lifecycle, they are not different from any other variable: if the function is no longer reacheable, it will be garbage collected at some point. For example, a function inside this block do local func = function() end end is not reachable from outside of the block and will be collected.

The example you have shown creates a coroutine, which takes a function and creates a value of type thread: type(coroutine.create(function() end)) == "thread". These coroutines may be in different states and their state is returned by coroutine.status function; in your case it's going to be "suspended".

Upvotes: 5

SwiftMango
SwiftMango

Reputation: 15294

A function has the type of function. In Lua, functions are first class citizen: First-Class Function

In actual memory, the function is just some block of memory that contains set of commands (similar to any other type e.g. integers)

Upvotes: 0

Related Questions