PHP - Lua::assign() Function
The PHP Lua::assign() function is used to transfer data from PHP to Lua scripts. Lua is a lightweight scripting language that can be used in applications. This function makes it easier to assign values to Lua variables from PHP code. It is a part of the easy scripting connection between PHP and Lua.
The allocated data can be strings, numbers, or even arrays. This is useful when PHP and Lua need to work together on a project. Lua::assign() allows data transfer between these two languages.
Syntax
Below is the syntax of the PHP Lua::assign() function −
public mixed Lua::assign( string $name , string $value )
Parameters
Here are the parameters of the assign() function −
$name − This is a string that represents the variable in the Lua script.
$value − The value you want to assign to the Lua variable.
Return Value
The assign() function returns a mixed value, which can be TRUE on success or FALSE if the assignment fails.
PHP Version
The assign() function is available from version 0.9.0 of the PECL lua extension onwards.
Example 1
This program shows how to assign a simple string from PHP to a Lua variable using the PHP Lua::assign() function. The Lua script results the value of the assigned variable.
<?php
$lua = new Lua();
// Assign a string to Lua variable
$lua->assign("greeting", "Hello, Lua!");
// Lua script retrieves and returns the variable
echo $lua->eval('return greeting;');
?>
Output
Here is the outcome of the following code −
Hello, Lua!
Example 2
In the below PHP code we will use the assign() function and assigning and manipulating a given number. So we will basically assign a number to a Lua variable and performs a mathematical operation in the Lua script.
<?php
$lua = new Lua();
// Assign a number as a string to Lua variable
$lua->assign("number", "5");
// Multiply the number in Lua and return the result
echo $lua->eval('return number * 2;');
?>
Output
This will generate the below output −
10
Example 3
Now in the below code we are using the Lua::assign() method and use an array to access its elements in a Lua script. So basically we will decode JSON in Lua and format the string.
<?php
$lua = new Lua();
// Assign a JSON string
$lua->assign("data", json_encode(["name" => "Anil", "age" => 30]));
// Decode JSON in Lua and format the string
echo $lua->eval('local data = cjson.decode(data); return data.name .. " is " .. data.age .. " years old.";');
?>
Output
This will create the below output −
Anil is 30 years old.