PHP - Lua::eval() Function



The PHP Lua::eval() function is used to evaluate a string as Lua code. By using this method, you can take advantage of PHP's compatibility with Lua, a lightweight programming language. This function is currently not documented; only its parameters list is available.

Syntax

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

public mixed Lua::eval( string $statements )

Parameters

This function accepts $statements parameter which is the Lua code you want to evaluate. The code has to be given as a string.

Return Value

The eval() function returns the result of evaluated code, NULL for wrong arguments, or FALSE on failure.

PHP Version

The eval() function is available from version 0.9.0 of the PECL lua extension onwards.

Example 1

Here is the basic usage of the PHP Lua::eval() function to execute simple Lua code like a mathematical calculation. Here we are calculating the sum of 2 numbers inside the function.

<?php
   // Create a Lua instance
   $lua = new Lua();

   // Evaluate a simple Lua expression
   $result = $lua->eval("return 5 + 3");

   // Output the result
   echo "Result: $result"; 
?>

Output

Here is the outcome of the following code −

Result: 8

Example 2

In the below PHP code we will use the eval() function to use variables in Lua code. The output of the program is the result of the addition, which is thirty. This shows how PHP can run Lua scripts and make use of the output.

<?php
   // Create a Lua instance
   $lua = new Lua();

   // Lua code with a variable
   $luaCode = "local a = 10; local b = 20; return a + b";

   // Evaluate the Lua code
   $result = $lua->eval($luaCode);

   // Output the result
   echo "Result: $result"; 
?> 

Output

This will generate the below output −

Result: 30

Example 3

This example shows how to use eval() function for evaluating Lua code which creates and manipulates a Lua table just like an array in PHP.

<?php
   // Create a Lua instance
   $lua = new Lua();

   // Lua code to create and access a table
   $luaCode = "
      local tbl = {10, 20, 30}
      return tbl[2]
   ";

   // Evaluate the Lua code
   $result = $lua->eval($luaCode);

   // Output the result
   echo "Result: $result"; 
?> 

Output

This will create the below output −

Result: 20

Example 4

In the following example, we are using the eval() function to evaluate Lua code which defines and calls a function in Lua.

<?php
   // Create a Lua instance
   $lua = new Lua();

   // Lua code defining and executing a function
   $luaCode = "
      local function multiply(x, y)
         return x * y
      end
      return multiply(7, 6)
   ";

   // Evaluate the Lua code
   $result = $lua->eval($luaCode);

   // Output the result
   echo "Result: $result";
?> 

Output

Following is the output of the above code −

Result: 42
php_function_reference.htm
Advertisements