PHP code example of developgravity / lua-ext

1. Go to this page and download the library: Download developgravity/lua-ext library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

developgravity / lua-ext example snippets




declare(strict_types=1);

use DevelopGravity\LuaExt\Sandbox;

$sandbox = new Sandbox();

$sandbox->registerLibrary('host', [
    'greet' => fn (string $name): string => "Hello, {$name}!",
]);

[$greeting] = $sandbox->eval('return host.greet("World")');

$doublerChunk = $sandbox->compile('return function(value) return value * 2 end', chunkName: 'double.lua');
[$doubleFunction] = $doublerChunk->call();
[$doubled] = $doubleFunction->call(21);

$sandbox->close();



declare(strict_types=1);

use DevelopGravity\LuaExt\LuaMethod;
use DevelopGravity\LuaExt\Sandbox;

final class TextService
{
    #[LuaMethod]
    public function upper(string $inputText): string
    {
        return strtoupper($inputText);
    }
}

$sandbox = new Sandbox();
$sandbox->registerObject('text', new TextService());

[$shouted] = $sandbox->eval('return text.upper("hi there")');



declare(strict_types=1);

use Carbon\CarbonImmutable;
use DevelopGravity\LuaExt\LuaClass;
use DevelopGravity\LuaExt\LuaOperator;
use DevelopGravity\LuaExt\Operator;
use DevelopGravity\LuaExt\Sandbox;
use DevelopGravity\LuaExt\SandboxConfig;

#[LuaClass(
    luaName: 'Carbon',
    methods: ['parse', 'now', 'copy', 'addDays', 'format'],
    operators: ['lessThan' => Operator::LessThan],
)]
final class LuaCarbon extends CarbonImmutable
{
    // New methods may carry attributes — only inherited ones cannot.
    #[LuaOperator(Operator::Add)]
    public function plus(self $other): static
    {
        return $this->addSeconds($other->getTimestamp());
    }
}

$config = new SandboxConfig(classes: [LuaCarbon::class]);
$sandbox = new Sandbox($config); // the Carbon table is ready, nothing else to call