PHP - Lua::registerCallback() Function



The PHP Lua::registerCallback() function is used to allow PHP functions to be linked to Lua. It means that a PHP function can be called by your Lua script. It is helpful for allowing simple communication between Lua scripts and PHP code.

This method involves creating a PHP function with Lua after it has been defined. After registering, Lua can use the function as if it were its own. This will be useful for applications that combine PHP and Lua.

Syntax

Below is the syntax of the PHP Lua::registerCallback() function −

public Lua::registerCallback ( string $name, callable $function )

Parameters

Here are the parameters of the registerCallback() function −

  • $name − This is the name you want to give the Lua callback function. It must be a valid string since it will be used to call the PHP function from Lua scripts.

  • $function − It can be a class method, anonymous function, or standard function as long as it can be called.

Return Value

The registerCallback() function returns $this, NULL for invalid arguments, or FALSE for other failures.

Example 1

This program shows how to register a simple PHP function as a Lua callback using the PHP Lua::registerCallback() function. The Lua script adds two numbers using the registered PHP function.

<?php
   // Include Lua extension
   $lua = new Lua();

   // Define a simple PHP function
   function addNumbers($a, $b) {
      return $a + $b;
   }

   // Register the function as a Lua callback
   $lua->registerCallback('add', 'addNumbers');

   // Lua script calling the PHP function
   $lua->eval('result = add(5, 10)');
   echo $lua->result; 
?>

Output

Here is the outcome of the following code −

15

Example 2

This example uses an anonymous function called registerCallback() to calculate the square of a value. Lua talks with the anonymous PHP function via the callback.

<?php
   // Include Lua extension
   $lua = new Lua();

   // Register an anonymous function as a Lua callback
   $lua->registerCallback('square', function ($number) {
      return $number * $number;
   });

   // Lua script using the callback
   $lua->eval('result = square(6)');
   echo $lua->result; 
?> 

Output

This will generate the below output −

36

Example 3

This program registers a class method as a Lua callback. The class method calculates a number's factorial, which Lua invokes using the callback.

<?php
   // Include Lua extension
   $lua = new Lua();

   // Define a class with a static method
   class MathHelper {
      public static function factorial($n) {
         return ($n === 0 || $n === 1) ? 1 : $n * self::factorial($n - 1);
      }
   }

   // Register the class method as a Lua callback
   $lua->registerCallback('factorial', ['MathHelper', 'factorial']);

   // Lua script calling the method
   $lua->eval('result = factorial(5)');
   echo $lua->result; 
?> 

Output

This will create the below output −

120
php_function_reference.htm
Advertisements