
The end result is a surprisingly small game file- a is only 127 lines long-for a pseudographical, procedurally generated interactive game, albeit a simple one.Īt long last, we’re ready to give EatyGuy a reason for all that running around: Let’s add some baddies! player:draw(grid)įor the most part, the extraction either replaces code with a method call, or removes a function altogether in the case of can_move_in_dir(). Player.chars = draw_data - Draw the player and baddies. Local framekey = math.floor(clock / anim_timestep) % 2 + 1 framekey switches between 1 & 2 basic sprite animation. It's been at least move_delta seconds since the last - time things moved, so let's move them now! player:move_if_possible(grid) Next_move_time = next_move_time + move_delta If state.clock < next_move_time then return end The can_move_in_dir() function is removed. You could use this class in another Lua file by running the following code: Let’s use a code pattern that is simple yet works well with single inheritance. Let’s also use the word method to refer to functions that are defined as part of a class.īecause Lua provides only low-level devices from which coders build classes, different class implementations are possible. As is common in some languages, we’ll capitalize the names of classes and class-like userdata. This is a great opportunity to implement a class–subclass relationship: the player and baddies can share a common superclass that we’ll call Character, whereas the baddy-specific behavior will live in subclass called Baddy.


Let’s call them baddies because it sounds more fun.

In this chapter, we add enemies to EatyGuy. Because of this, I’ll cover Lua classes in more detail than I’ve previously covered other language features. This is due to the fact that classes in Lua are not directly supported by the language rather, they are enabled by giving coders the low-level pieces needed to be assembled into class mechanics. Nonetheless, Lua does ask for some depth of thought when it’s time to implement classes and class inheritance. Most of Lua’s design is simple and transparent, including the building blocks of Lua’s class system. EatyGuy Version 6: Writing a Class in Lua
