Alex L
Alex L

Reputation: 115

Lua local variable assignment

I have been looking at some Lua code recently and multiple times the author assigns a local variable, altering the local variable seemingly with the expected outcome of also altering the assigning variable as he does not do anything with the local variable after. Is this the case or do these changes not affect the original values.

Gene Construct

local gene = {}
gene.into = 0
gene.out = 0
gene.weight = 0.0
gene.enabled = true
gene.innovation = 0`

Code

function nodeMutate(genome)
if #genome.genes == 0 then
    return
end

genome.maxneuron = genome.maxneuron + 1

local gene = genome.genes[math.random(1,#genome.genes)]
if not gene.enabled then
    return
end
gene.enabled = false

local gene1 = copyGene(gene)
gene1.out = genome.maxneuron
gene1.weight = 1.0
gene1.innovation = newInnovation()
gene1.enabled = true
table.insert(genome.genes, gene1)

local gene2 = copyGene(gene)
gene2.into = genome.maxneuron
gene2.innovation = newInnovation()
gene2.enabled = true
table.insert(genome.genes, gene2)
end

Upvotes: 0

Views: 1078

Answers (2)

nobody
nobody

Reputation: 4264

From my reading of the code I'd think the following:

local gene1 = copyGene(gene)  -- local copy, distinct from original 'gene'
-- (modifications of 'gene1')
table.insert(genome.genes, gene1) -- add modified copy to 'genome.genes'

So I'd guess that copyGene produces a copy of gene, meaning that gene isn't modified (only gene1, gene2). References to these are held in local variables and these references indeed go out of scope at the end of the block. But the modified copy is added to the list (/ array / sequence, whatever you want to call it) genome.genes which does produce an externally visible effect (because that variable – genome – comes in from outside).

My higher-level impression of the code is that genome.genes is a list of genes that may or may not be enabled. Each run through this function randomly picks one of these genes and if it is enabled, (1) disables it and (2) adds two modified enabled copies to the genome.genes (which may then be the base for new copies in later runs).

Upvotes: 0

Adam
Adam

Reputation: 3103

Changes to gene may affect genome.genes[math.random(1,#genome.genes)] because gene is a reference. From the Lua Manual - Values and Types:

Tables, functions, threads, and (full) userdata values are objects: variables do not actually contain these values, only references to them. Assignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any kind of copy.

This means that when you assign a variable to an object you copy the reference to that object, not the object itself.

For example:

local a = {1,2,3}
local b = a
b[1] = 'a'

The table a now contains {'a',2,3} because b is a reference to a.

Upvotes: 3

Related Questions