Lua 5.2.4: If statement syntax error, I can't find anything wrong with my code

I'm messing around with some simple lua programming just for fun. The program I'm working on is simply supposed to take a single argument and print the relationship to oneself based on a number line. It's just a couple of simple formulae and a function to build and print strings from the data.

My problem is that every single 'if' statement in my program is coming back with the error " '=' expected near 'if' "

So far I've tried seeing if there's a known version issue (there isn't and I don't know why there would be)

I've messed around with my if statements, tried different comparators, replaced all variables with literals, stripped down to single clause statements, and none of this is working.

This is my first attempt to run lua from a terminal. In the past I've only written lua for Defold, and never run into something like this.

I'll put one instance of the issue as an example:

function number_of_greats(generation)
    local var g = math.abs(generation)
    local var num_greats

    if generation > -2 or generation then
        num_greats = 0
        num_greats = g-2

    return num_greats

the error is "expected '=' near 'if'"

the expected result is that the function returns either result for the function G(gen) depending on the range gen fits in.

generation is a position on a number. Negative represents ancestors, positive represents successors.

the mathematical function is:

G(gen) = |gen| - 2 for gen < -2 and gen > 2
G(gen) = 0 for -2 < gen < 2
G(gen) is the number of "greats" in the relationship title

1 answer

  • answered 2019-09-10 14:51 Nifim

    You do not need the term var in your definitions of variables in lua.

    If you remove them your code with run without errors.

    Lua is a dynamically typed language. There are no type definitions in the language; each value carries its own type.

    Programming in Lua: 2 – Types and Values

    In Lua you do not declare the type of a variable, instead you let the value of the variable define the type.

    This means it is not necessary to do:

    local number i = 7
    local boolean check = false
    local string str = "hello world"

    instead you do

    local i = 7
    local check = false
    local str = "hello world"

    Now both of the above code chunks will run with no errors, however the first one only does so because we apply a value to the variables. If we remove the assignment we get and error:

    local number i

    I was not able to find why the assignment makes this "acceptable". I believe it is because Lua is throwing out the first variable "name" being number and proceeds with the second i.

    function is a bit different as you can write the definition a few different ways:

    local function x(y)

    but the above is just syntactic sugar for:

    local x = function(y)

    Programming in Lua: 6 – More about Functions