Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

Advanced Lua - Part I

Icon Leave Comment
Coming soon to a tutorial section near you!

Abstract

Quote

Prerequisites:

This tutorial assumes you have some basic programming knoweldge (i.e. I won't explain what a variable/function is) and have a solid understanding of the fundamentals of Lua. If you need a brush up see The Introduction to Lua series (Parts I, II, III, and IV). Let's get started!

Closures

As noted in a previous tutorial, a function inside of another function has full access to the local variables of the enclosing function. As you may remember this is called lexical scoping. Also, functions are first class values, meaning that they have the same abilities, features, and possible behavior of variables (i.e. numbers and strings). With these two combined, we (the programmers) are allowed powerful access to features many other programming languages do not support. In a manner, we are transcending between traditional programming languages and functional programming languages.

--a lead in example
--sort function
function sortGrades(names, grades)
table.sort(names,
	function(n1, n2)
		return grades[n1] > grades[n2]
	end)
end

--data
names = {"Knowles", "Joe", "Mary"}
grades = {Knowles = 100, Joe = 87, Mary = 96}

--unsorted table
for i,v in ipairs(names) do
	print(v)
end

sortGrades(names, grades)
print()
print()

--sorted table
for i,v in ipairs(names) do
	print(v)
end


Tail Calls

Another neat feature Lua has is tail-call elimination. A tail-call occurs when a function calls another as its last action:

function foo(x)	 return goo(x)	 end	 --tail call returning goo(x)


After calling function goo(), foo() has nothing left to do. It is evident that the program does not "have" to return to foo after executing goo() because there is nothing left except returning from foo(). The Lua interpreter takes advantage of this ability and will return control to right after where foo() was called once goo() finishes up. No extra stack space is needed, so a program can make as many tail calls as it wants.

...


Read the full post HERE

0 Comments On This Entry

 

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    18 user(s) viewing

    18 Guests
    0 member(s)
    0 anonymous member(s)