Adding Events

This thread is very useful when learning the basics in Civ V lua programming. I would like to see more working examples in simple lua code. For example things like changing the yield or maintenance of a building, after a specific tech is acquired.

An easy lua tutorial would be nice. There are lots of modders out there who play with XML. If only some of them were able to use lua properly, we could see more powerful mods.
 
An easy lua tutorial would be nice.

Look at Programming in Lua: http://www.lua.org/pil/
The online free version targets Lua 5.0, which is somewhat outdated, but it's worth reading (not the 4th Part, but mostly all the others).

There's also partially free online avaible Lua Programming Gems http://www.lua.org/gems/
It's a bit harder to read, and not so useful for us, but please! read the Lua Performance Tips by Roberto Ierusalimschy ( http://www.lua.org/gems/sample.pdf ) -- and this should do all modders.

You really don't need to do much for optimize your Lua-code, just few things i see in likely every mod:

1.You need to compare with nil only, and really only if You need to distinguish between nil and false:
Code:
local x = 42
if x ~= nil then  print'x~=nil' end
if x then print'x~=nil w/o comparsion that costs CPU time' end

x = nil
if x == nil then print'now it is nil' end
if x then print'this print is skipped' end
if not x then print'but this is not!' end
2. Use locals. They are fast.
2.a. If You are using a function/table/tablekey(read-only) a lot, make a local of it. In a mod i'm working on it looks like that:
Code:
somef = function(self)
local self_m_Instance = self.m_Instance
-- here some bad loop
    --...
    self_m_Instance.things:DoSomething()
    self_m_Instance.otherthings:DoSomethingElse()
    --...
    self_m_Instance[somekey]:SetHide(true)
    --...
    -- and so on many times
-- end of the loop
end -- of function
3. Avoid using table.insert. It's slow, and seldom needed. A good way to append a value to array is:
Code:
local t = {}
for i = 42,666 do t[#t+1]=i end
4. Make use of Lua's lazy evaluation:
Code:
local f = function() -- some costly function
    local j
    for i = 1, 10e10 do
        j = j + i*i
    end
    return j > 10e20
end
local cond = true -- some condition

if f() or cond then -- wrong order, f evaluated always
    print'f() or cond'
end

if cond or f() then -- right order, f evaluated only if cond is false
    print'cond or f()'
end

Surely, optimization hurts readability. But above "tricks" in most cases are harmless to it but can improve performance a lot. And CiV already needs a lot of PC resources.
 
Top Bottom