Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to emulate bind in Lua?

Tags:

lua

Given a lua function with one argument, is it possible to bind this argument to a fixed value to obtain a function without arguments?

More generally, how do I bind certain input arguments of a lua function to certain values?

like image 736
Benno Avatar asked Jun 20 '12 10:06

Benno


People also ask

How many functions does Lua have?

This means that all values can be stored in variables, passed as arguments to other functions, and returned as results. There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table.

What is a Lua state?

A Lua state is a C pointer to an opaque data structure. This structure knows everything about a running Lua environment, including all global values, closures, coroutines, and loaded modules. Virtually every function in Lua's C API accepts a Lua state as its first parameter.

What does bind in JavaScript mean?

bind is a method on the prototype of all functions in JavaScript. It allows you to create a new function from an existing function, change the new function's this context, and provide any arguments you want the new function to be called with.


1 Answers

Yes, this can be done in pretty much any language that have functions as first-class values.

function f1(a)
   return a+1
end

function bind(a)
   return function() return f1(a) end
end

local f2 = bind(42)
print(f2())
-- 43

This particular example works with specific function and number of arguments, but can easily be extended to take arbitrary function/arguments instead.

like image 90
Oleg V. Volkov Avatar answered Nov 26 '22 21:11

Oleg V. Volkov