Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Function with Variable Argument

lua

function average(...)
   result = 0
   local arg = {...}
   for i,v in ipairs(arg) do
      result = result + v
   end
   return result/#arg
end

print("The average is",average(10,5,3,4,5,6))

Assigning and Passing Functions

lua

myprint = function(param)
   print("This is my print function -   ##",param,"##")
end

function add(num1,num2,functionPrint)
   result = num1 + num2
   functionPrint(result)
end

myprint(10)
add(2,5,myprint)

Calling Function

lua

function max(num1, num2)

   if (num1 > num2) then
      result = num1;
   else
      result = num2;
   end

   return result; 
end

-- calling a function
print("The maximum of the two numbers is ",max(10,4))
print("The maximum of the two numbers is ",max(5,6))

Lua nested if Statement

lua

--[ local variable definition --]
a = 100;
b = 200;

--[ check the boolean condition --]

if( a == 100 )
then
   --[ if condition is true then check the following --]
   if( b == 200 )
   then
      --[ if condition is true then print the following --]
      print("Value of a is 100 and b is 200" );
   end
end

print("Exact value of a is :", a );
print("Exact value of b is :", b );

if else Statement in Lua

lua

--[ local variable definition --]
a = 100;

--[ check the boolean condition --]

if( a < 20 )
then
   --[ if condition is true then print the following --]
   print("a is less than 20" )
else
   --[ if condition is false then print the following --]
   print("a is not less than 20" )
end

print("value of a is :", a)

if Statement in Lua

lua

--[ local variable definition --]
a = 10;

--[ check the boolean condition using if statement --]

if( a < 20 )
then
   --[ if condition is true then print the following --]
   print("a is less than 20" );
end

print("value of a is :", a);

break Statement in Lua

lua

--[ local variable definition --]
a = 10

--[ while loop execution --]
while( a < 20 )
do
   print("value of a:", a)
   a=a+1
	
   if( a > 15)
   then
      --[ terminate the loop using break statement --]
      break
   end
	
end

nested Loop in Lua

lua

j = 2
for i = 2,10 do
   for j = 2,(i/j) , 2 do
	
      if(not(i%j)) 
      then
         break 
      end
		
      if(j > (i/j))then
         print("Value of i is",i)
      end
		
   end
end

repeat until Loop in Lua

lua

--[ local variable definition --]
a = 10

--[ repeat loop execution --]
repeat
   print("value of a:", a)
   a = a + 1
until( a > 15 )

For Loop in Lua

lua

for i = 10,1,-1 
do 
   print(i) 
end

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.