JS right arrow LUA

A guide to converting syntax from JS to LUA

Functions

Lua uses keyword...end blocks instead of {}.

JS
function sayHello(name) {
    return name
}

sayHello("gan")
Lua
function sayHello(name)
    return name
end

return sayHello("gus")

Comments

JS
// single line comment
/*
    multiline comment
*/
Lua
-- single line comment
--[[
    multiline comment
--]]

do .. while

JS
do {
    // some code
} while (condition)
Lua
repeat
    -- some code
until not condition

Variable

All local variables in lua use local instead of var, let, or const.

JS
var a = 1
let b = 2
const c = 3
d = 4 // global
Lua
local a = 1
local b = 2
local c = 3
d = 4 -- global

Equality

JS
let bool1 = "0" === 0 // false
let bool2 = "0" == 0  // true
Lua
local bool1 = "0" == 0            -- false
local bool2 = "0" == tostring(0)  -- true

Negation Operator

JS
let isNotFrance = country != "france"
Lua
local isNotFrance = country ~= "france"

Ternary

JS
let name = condition ? "A" : "B"
Lua
local name = condition and "A" or "B"

-- safer
if condition then
    name = "A"
else
    name = "B"
end

Null-Coalescing Operator

JS
let message = error.message ?? 'An unknown error occurred.';
let message = error.message ? error.message : 'An unknown error occurred.';
Lua
local message = error.message or 'An unknown error occurred.';

Multiple Expressions

JS
const variable = (someExpression1, someExpression2, ..., someExpressionN)
Lua
local variable = (function()
    someExpression1
    someExpression2
    ...
    return someExpressionN
end)()

Unicode

Lua only supports up to UTF-8

JS has String.fromCharCode()

JS
let a1 = "a"
let a2 = "\u{061}"
let a3 = "\u0061"
let a4 = String.fromCharCode(0x61) // hex
let a5 = String.fromCharCode(97)   // dec
Lua
local a1 = "a"
local a2 = "\u{061}"
local a3 = "\097"
local a4 = string.char(0x61) -- hex
local a5 = string.char(97)   -- dec
local a6 = utf8.char(0x61)   -- hex
local a7 = utf8.char(97)     -- dec

Further Reading