Lua study notes

The official version of neovim 0.5 has been released. Now it's time to learn Lua language. Lua replacing vim scripts is becoming a trend.

After learning, Lua feels very similar to javascript. The code block is not divided by {}, but end. You need to get used to it. Code reading is not a big problem. You still have to adapt to writing your own code.

Lua has some interesting syntax, which is simpler and better than Java and Javascript!

My tutorial documents:
https://www.lua.org/pil/contents.html

The article is simple and clear. It is recommended to read.

table.sort sort sort

ip addresses are sorted by name

network = {
	{name = "grauna",  IP = "210.26.30.34"},
	{name = "arraial", IP = "210.26.30.23"},
	{name = "lua",     IP = "210.26.23.12"},
	{name = "derain",  IP = "210.26.23.20"},
}


table.sort(network,function (a,b)
	return (a.name > b.name)
end)

print("output")
for _,line in ipairs(network) do
	print(line.name)
end

Students are sorted by grade

names = {"Peter","Paul","Mary"}
grades= {Mary =10,Paul =7,Peter=8}

table.sort(names,function (n1, n2)
	return grades[n1] > grades[n2]
end)

print("------Output sorting results------")
for _,line in ipairs(names) do
	print(line)
end

Students are sorted by grade user-defined function

The interesting point in the example is that the given anonymous function sort accesses the parameter grades, which is a local sortbygrade for the closed function. Inside this anonymous function, grades is neither a global variable nor a local variable. We call it an external local variable or upvalue. (the term "upvalue" is a bit misleading because it grades is a variable, not a value. However, this term has a historical origin in Lua and is shorter than "external local variable")

names = {"Peter","Paul","Mary"}
grades= {Mary =10,Paul =7,Peter=8}

function sortbygrade(names,grades)
	table.sort(names,function(n1,n2)
		return grades[n1] > grades[n2]
	end)
end

sortbygrade(names,grades)

print("------Output sorting results------")
for _,line in ipairs(names) do
	print(line)
end

https://www.lua.org/pil/6.1.html

Closures

Lua version

This feature is different from what I thought.

So, c1 and c2 are different closures over the same function and each acts upon an independent instantiation of the local variable i. Technically speaking, what is a value in Lua is the closure, not the function. The function itself is just a prototype for closures. Nevertheless, we will continue to use the term "function" to refer to a closure whenever there is no possibility of confusion.

Therefore, c1 and c2 are different closures on the same function, and each closure acts on the independent instantiation i of the local variable. Technically, the values in Lua are closures, not functions. The function itself is just the prototype of a closure. Nevertheless, as long as there is no possibility of confusion, we will continue to use the term "function" to refer to closures.

function newCounter()
	local i = 0
	return function () --Anonymous function
		i = i + 1
		return i
	end
end

c1 = newCounter()
print(c1()) -->1
print(c1()) -->2

c2 = newCounter()
print(c2())  -->1
print(c1())  -->3
print(c2())  -->2

I haven't used this method before. In order to test my understanding, I wrote a javascript version. The execution result is the same. It seems that I have always understood that there is a problem.

Javascript version

The results are consistent with Lua version 1 to.

function newCounter(){
	let i = 0;
	return function(){
		i = i+1;
		return i;
	}
}

let c1 = newCounter()
console.log(c1()); //>1
console.log(c1()); //>2

let c2=newCounter()
console.log(c2());//>1
console.log(c1());//>3
console.log(c2());//>2

Java version

I thought about how to write similar code in Java? There seems to be no anonymous method in Java, right?

	public static void main(String[] args) {
        System.out.println(newCounter());//>1
        System.out.println(newCounter());//>1
        System.out.println(newCounter());//>1
    }

    public static int newCounter() {
        int i = 0;
        return i + 1;
    }

Obviously, this is wrong. It is estimated that it should be handled by anonymous inner classes.
In order to simulate the above logic, I use the class implementation in java. Implementation results 1 to.

public class Main {
    public static void main(String[] args) {
        class NewCounter{
            int i =0;
            public NewCounter() {
            }
            @Override
            public String toString() {
                i = i+1;
                return String.valueOf(i);
            }
        }
        NewCounter c1 = new NewCounter();
        System.out.println(c1);//>1
        System.out.println(c1);//>2

        NewCounter c2 = new NewCounter();
        System.out.println(c2);//>1
        System.out.println(c1);//>3
        System.out.println(c2);//>2
    }
}

Summary:
Variables in Closures feel similar to class properties in Java, and are managed separately by an instance.

Non-Global Functions

Writing method

Lib = {}
    Lib.foo = function (x,y) return x + y end
    Lib.goo = function (x,y) return x - y end

or

 Lib = {
      foo = function (x,y) return x + y end,
      goo = function (x,y) return x - y end
    }

or

Lib = {}
    function Lib.foo (x,y)
      return x + y
    end
    function Lib.goo (x,y)
      return x - y
    end

Definition of recursive local function

FALSE ❌

local fact = function (n)
      if n == 0 then return 1
      else return n*fact(n-1)   -- buggy
      end
    end

correct ✅

 local fact
    fact = function (n)
      if n == 0 then return 1
      else return n*fact(n-1)
      end
    end

Now inside the fact function refers to local variables. Its value when defining a function is irrelevant; By the time the function executes, fact already has the correct value. This is how Lua extends its syntax sugar for native functions, so you can use it for recursive functions without worrying about:

 local function fact (n)
      if n == 0 then return 1
      else return n*fact(n-1)
      end
    end

Related documents

https://www.lua.org/pil/contents.html#P1

Tags: lua

Posted on Fri, 24 Sep 2021 18:50:33 -0400 by ctsttom