Skip to Content
Beginning Lua Programming
book

Beginning Lua Programming

by Kurt Jung, Aaron Brown
February 2007
Beginner
672 pages
15h 34m
English
Wrox
Content preview from Beginning Lua Programming

Chapter 8. Extending Lua's Behavior with Metamethods

You use metatables and metamethods mainly to create what can, loosely speaking, be described as user-defined types. For example, if you have defined a table that represents a number-like value, metamethods let you use arithmetical operators with it as though it really were a number. In this chapter, you learn how to do the following:

  • Use operators with types that they normally don't work with

  • Control what happens when a table is indexed or a table field is assigned to

  • Customize how a value is converted to a string

Using Concatenation and Arithmetical Operators on Tables

If you use tables as operands to the concatenation operator, you get the following error:

> A, B = {}, {}
> print(A .. B)
 stdin:1: attempt to concatenate global 'A' (a table value)
 stack traceback:
         stdin:1: in main chunk
         [C]: ?

There's a way to override this, though, so the concatenation operator is handled by a function that you define.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Lua Quick Start Guide

Lua Quick Start Guide

Gabor Szauer
The Go Programming Language

The Go Programming Language

Alan A. A. Donovan, Brian W. Kernighan

Publisher Resources

ISBN: 9780470069172Purchase book