Python to Lua Cheat Sheet

My first impression: Lua has somehow similar syntax to Python but there are enough differences to make this confusing. So here is my Python to Lua cheat sheet:

Miscellaneous

--single line comment in lua
--[[
what the f* is this?
I need to get rid of my german keyboard
or never use multiline comments in lua...
--]]

print('parentheses are mandatory as in python 3')

--not equal in lua
~=

--true and false is lowercase

--None is Nil in Lua

Variables

--variables are global by default, they can be made local with local
local var = 20
local my_string = "string with double quotes"
local another_string = 'single quotes work just as well - sweet!'
local string_concatenation = my_string .. another_string

if and for

if and for syntax reminds me of good ol’ max script. Since Lua doesn’t rely on indentations it requires simple keywords instead like “do”, “then” or “end”. “elif” becomes the slightly longer “elseif”.

--if expression
if var == 20 then
print ('this is equal')
elseif var > 20 then
print ('this is larger')
else
print ('then it must be smaller')
end

--for loop
for start, end, step do
something
end

--this starts at 2 and increments by 1 until 5
for i=2, 5, 1 do
print(i)
end

lists, arrays, dicts = tables

Lua has meta-mechanism. For example python doesn’t have a native array, but you can use lists to make one. Lua goes a step further. Lua just has tables which could behave like a list, an array or even a dict, depending on how you define/use it.

--index starts at 1 not 0
--curly brackets instead of square, however square ones for accessing it.

local list = {1,2,3}
print(list[2])

local array = {{1,2},{3,4}}
print(array[2][1])

local dict = {first_key = 123, second_key = 456}
print(dict.first_key)

--yup, every one of those is just a table in Lua

functions

function my_function(arg)
print(arg)
end

my_function('hello lua')

random code snippets

--iterate over a list
for i, l in ipairs(list) do
print(l)
end

--iterate over an array and print the first item
for i, a in ipairs(array) do
print(a[1])
end


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *