cfrancklin
cfrancklin

Reputation: 315

Trying to understand Lua simple codes

I'm having some trouble with Lua. The thing is: there are some Lua codes I know what they do but I didn't understood them, so if the professors ask me to explain them, I wouldn't be able to do it. Can you help me with this?

  1. I know this code separates the integer part from the decimal part of a number, but I didn't understand the "(%d*)(%.?.*)$" part.

    int, dec = string.match(tostring(value), "(%d*)(%.?.*)$")
    
  2. This code insert on a table all the data from a text file, which is written following this model entry {name = "John", age = 20, sex = "Male"). What I didn't understand is how do I know what parameters the function load needs? And the last parameter entry = entry, I don't know if I got exactly its meaning: I think it gets the text_from_file as a piece of Lua code and everything that is after entry is sent to the function entry, which inserts it on a table, is it right?

    function entry(entrydata)
        table.insert(data, entrydata)           
    end
    
    thunk = load(text_from_file, nil, nil, {entry = entry})
    thunk()
    

That's it. Please, if it's possible, help me understand these 2 pieces of Lua code, I need to present the whole program working and if a professor ask me about the code, I want to be sure about everything.

Upvotes: 3

Views: 123

Answers (1)

hjpotter92
hjpotter92

Reputation: 80639

For the first question, you need to learn a little about lua patterns and string.match.

The pattern (%d*)(%.?.*)$ is comprised of two smaller ones. %d* and %.?.*. The $ at the end merely indicates that the matching is to be done till the end of string tostring(value). The %d* will match 0 or more numerical values and store the result (if found, otherwise nil) t the variable int.

%.? matches a literal . character. The ? means that the . may or may not be present. The .* matches everything and stores them into dec variable.


Similarly, for the second code segment, please go through the load() reference. You have the following text in your file:

entry {name = "John", age = 20, sex = "Male")

It is equivalent to executing a function named entry with the parameter (notice that I used parameter and not parameters) a table, as follows:

entry( {name = "John", age = 20, sex = "Male") )

The last parameter to load defines the environment for the loaded string. By passing {entry = entry}, you're defining an environment in which you have a function named entry. To understand it better, look at the changes in the following segment:

function myOwnFunctionName(entrydata)
    table.insert(data, entrydata)
end

thunk = load(text_from_file, nil, nil, {entry = myOwnFunctionName})

Now, the custom environment passed to load will have a variable named entry which is actually the function myOwnFunctionName.

Upvotes: 2

Related Questions