Skip to main content

Learning Lua

Note: This is a very basic lua tutorial to get you familiar with NvChad config

Printing#

print("Hi")

Comments#

-- a commentprint("hi") -- another comment

Variables#

-- Different typeslocal x = 10 -- numberlocal name = "Sid" -- stringlocal isAlive = true -- booleanlocal a = nil --no value or invalid value

Numbers

-- exampleslocal a = 1local b = 2
print(a + b) -- 3
-- incrementlocal level = 1level = level + 1print(level) -- 2

Strings

-- concatenate stringslocal phrase = "I am"local name = "Sid"print(phase .. name) -- I am Sid
-- strings and numberslocal name = "NvChad"print(name .. "v" .. 1.0) -- NvChad v1.0

Boolean

local isAlive = trueprint(isAlive) -- true
isAlive = falseprint(isAlive) -- false

Comparison Operators

  • == equality
  • < less than
  • > greater than
  • <= less than or equal to
  • >= greater than or equal to
  • ~= inequality

Conditional Statements#

-- number comparisionslocal age = 10
if age > 18 then  print("over 18") -- this will not be executedend
-- elseif and elseage = 20
if age > 18 then  print("over 18")elseif age == 18 then  print("18 huh")else  print("kiddo")end
-- boolean comparisionlocal isAlive = true
if isAlive then    print("Be grateful!")end
-- string comparisionslocal name = "sid"
if name ~= "sid" then  print("not sid")

Combining Statements

local age = 22
if age == 10 and x > 0 then -- both should be true  print("kiddo!")elseif x == 18 or x > 18 then -- 1 or more are true  print("over 18")end
--result: over 18 

Invert Value

you can also invert a value with the not keyword

local x = 18
if not x == 18 then  print("kiddo!")end

Functions#

function num(a)  print(a)end
or 
local num = function(a)   print(a)end
num(5)
-- result : 5
-- multiple parameters
function sum(a + b)  local result = a + b  print(result)end

Scope#

Variables have different scopes. Once the end of the scope is reached the values in that scope are no longer accessable

function foo()  local n = 10end
print(n) -- nil , n isnt accessable outside foo()

Loops#

Different ways to make a loop

-- while looplocal i = 0
while i <= 3 do   print("hi")   i = i + 1end
OR
--for loopfor i = 0, 3 do   print("hi")   i = i + 1end
-- result hi  hi  hi

Tables#

-- basic tablelocal colors = { "red", "green", "blue" }
print(colors[1]) --redprint(colors[2]) --greenprint(colors[3]) --blue
-- use a loop to iterate though the tablefor i=1, #colors do  print(colors[i])end

Two Dimensional Table

--tables within tableslocal data = {    { "billy", 12 },    { "john", 20 },}
for i = 1, #data do  print(data[i][1] .. " is " .. data[i][2] .. " years old")end

Modules#

Include code other files

require("otherfile")
  • Credits - Modified version of this guide