xiangnanscu / js2lua

js2lua Writing LuaJIT with the expressiveness of JavaScript.
https://xiangnanscu.github.io/js2lua/
3 stars 0 forks source link

Question: how to make global functions without exports #6

Open al1-ce opened 5 days ago

al1-ce commented 5 days ago

How to get following code?

function func() end
xiangnanscu commented 4 days ago

You need to provide JS code cases first

al1-ce commented 4 days ago

Simple, imagine having a big library of util functions

// big_lib.js
function pack2(a, b) {
    return [a, b];
}

function pack3(a, b, c) {
    return [a, b, c];
}

// ...some code between... 

function has_module(mod_name) {
    return pack2(pcall(require, mod_name))[1];
}

I could make them all exports, but it'd damage brevity

// exports
let somelib = require("somelib");

print(somelib.has_module("otherlib"));

vs

// global
require("somelib")

print(has_module("otherlib"));
xiangnanscu commented 4 days ago

To make things clear, there're two use cases for this repo:

  1. Porting existing JS code to lua.
  2. Just writing lua code but want a more expressive syntax like JS.

If the first one, problem doesn't exist because JS lib must write export statement if it want to export something. If no export code, then nothing should be exported, nothing global shoud be defined. If the second one, I know you want the JS lib function declarations behave like lua global function declarations. But that will conflict with the first one. Unless a mechanism is designed that allows for explicit declaration in JavaScript code "I want this JavaScript function to be converted into a global Lua function".

al1-ce commented 4 days ago

Actually with this there's actually a proper way to do it: var variables are defined in global scope and so I'd propose:

let a;
var b;

function c() {}
let d = function() {}
var e = function() {}
local a
b = nil

local function c() end
local d = function() end
e = function() end

I'm always surprised how world forgot about var like it never existed