SlideShare a Scribd company logo
Learn Lua For Ios Game Development 1st Ed Jayant
Varma download
https://ebookbell.com/product/learn-lua-for-ios-game-
development-1st-ed-jayant-varma-55199758
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Learn Lua For Ios Game Development 1st Ed Varma Jayant
https://ebookbell.com/product/learn-lua-for-ios-game-development-1st-
ed-varma-jayant-6618286
Lua Programming Beginners Learn Lua Programming Step By Step Very Easy
Rizk
https://ebookbell.com/product/lua-programming-beginners-learn-lua-
programming-step-by-step-very-easy-rizk-37070252
Lua Programming Beginners Learn Lua Programming Step By Step Very Easy
Rizk
https://ebookbell.com/product/lua-programming-beginners-learn-lua-
programming-step-by-step-very-easy-rizk-232145960
Learn Javafx Game And App Development With Fxgl 17 1st Edition Almas
Baimagambetov
https://ebookbell.com/product/learn-javafx-game-and-app-development-
with-fxgl-17-1st-edition-almas-baimagambetov-44879768
Learn C The Hard Way Practical Exercises On The Computational Subjects
You Keep Avoiding Like C Zed A Shaw
https://ebookbell.com/product/learn-c-the-hard-way-practical-
exercises-on-the-computational-subjects-you-keep-avoiding-like-c-zed-
a-shaw-44988700
Learn To Read Ancent Sumerian An Introduction For Complete Begiknners
Joshua Bowen
https://ebookbell.com/product/learn-to-read-ancent-sumerian-an-
introduction-for-complete-begiknners-joshua-bowen-45333320
Learn C Programming A Beginners Guide To Learning The Most Powerful
And Generalpurpose Programming Language With Ease 2nd Edition 2nd Jeff
Szuhay
https://ebookbell.com/product/learn-c-programming-a-beginners-guide-
to-learning-the-most-powerful-and-generalpurpose-programming-language-
with-ease-2nd-edition-2nd-jeff-szuhay-45462930
Learn Enough Ruby To Be Dangerous Write Programs Publish Gems And
Develop Sinatra Web Apps With Ruby Michael Hartl
https://ebookbell.com/product/learn-enough-ruby-to-be-dangerous-write-
programs-publish-gems-and-develop-sinatra-web-apps-with-ruby-michael-
hartl-46132216
Learn Guitar The Easy Way The Easy Way To Play Guitar Using Simplified
Chords Paolo Ocampo
https://ebookbell.com/product/learn-guitar-the-easy-way-the-easy-way-
to-play-guitar-using-simplified-chords-paolo-ocampo-46157382
Learn Lua For Ios Game Development 1st Ed Jayant Varma
Learn Lua For Ios Game Development 1st Ed Jayant Varma
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
v
Contents at a Glance
About the Author�������������������������������������������������������������������������������������������������������������� xxv
About the Technical Reviewers�������������������������������������������������������������������������������������� xxvii
Acknowledgments����������������������������������������������������������������������������������������������������������� xxix
Chapter 1: Introduction to Lua
■
■ 
�������������������������������������������������������������������������������������������1
Chapter 2: Lua Libraries
■
■ ��������������������������������������������������������������������������������������������������13
Chapter 3: File Operations
■
■ �����������������������������������������������������������������������������������������������29
Chapter 4: Math with Lua
■
■ ������������������������������������������������������������������������������������������������41
Chapter 5: Strings
■
■ �����������������������������������������������������������������������������������������������������������65
Chapter 6: Threading
■
■ �������������������������������������������������������������������������������������������������������77
Chapter 7: Tips and Tricks
■
■ �����������������������������������������������������������������������������������������������97
Chapter 8: Corona SDK
■
■ ��������������������������������������������������������������������������������������������������127
Chapter 9: Gideros Studio
■
■ 
����������������������������������������������������������������������������������������������167
Chapter 10: Moai
■
■ �����������������������������������������������������������������������������������������������������������203
Chapter 11: LÖVE
■
■ �����������������������������������������������������������������������������������������������������������245
Chapter 12: Codea
■
■ ���������������������������������������������������������������������������������������������������������279
vi Contents at a Glance
Chapter 13: Libraries
■
■ �����������������������������������������������������������������������������������������������������303
Chapter 14: Third-Party Applications
■
■ ����������������������������������������������������������������������������317
Chapter 15: Sample Source Code
■
■ ����������������������������������������������������������������������������������349
Index���������������������������������������������������������������������������������������������������������������������������������377
1
Chapter 1
Introduction to Lua
Apple has been issuing checks to developers, and the 2012 figures indicate that it has so far been
to the tune of $5 billion. In the past, it used to be desktops with Microsoft-based products that were
raking in money for developers, with Visual Basic, or earlier with database products such as dBase
and FoxPro. While the major share of this revenue goes to larger companies such as EA, Chillingo,
Gameloft, Rovio and even Disney, a lot of indie developers and smaller companies vie for a share of
that big pie. Who knows what idea might just become the money-spinner for a developer. Robert Nay,
a 14-year-old, made the game Bubble Ball while he was learning to code, and it went viral, with over
8 million downloads. And no one knows what the next top game will be.
As a person that has an interest in development, you have made the first step in this journey. You
could be a student that has never developed before, or you could be a guru developer who can
whip up an enterprise app in minutes. The point is that whatever your background, you are for some
reason drawn to this strange-sounding language, Lua (pronounced LOO-ah.).
What Is Lua?
Lua is a programming language that has a small footprint, works across several platforms, and is
quite flexible and extensible. Further, Lua is a game changer for developers that want to write apps
for the mobile devices. It has powered a lot of apps and games in the Apple App Store, and it has
been spoken about by the late Steve Jobs. It has even been linked with one of the most advanced
self-replicating and mutating viruses, the Flame. Despite all of that, Lua remains to be a language
that seems more like plain English than a cryptic programmer’s language, making it a language with
a smaller learning curve.
The History of Lua
While knowing the history of Lua will not change anything in terms of making anyone a better
programmer, it important to get an idea of why you’d want to use Lua.
Lua was created at the Pontifical Catholic University of Rio de Janeiro, Brazil, by Roberto
Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes, who were members of the
CHAPTER 1: Introduction to Lua
2
Computer Graphics Technology Group (TeCGraf). Generally, funding for university research is
provided by industry, which also expects solutions to some problems that they face. Petrobas, a
Brazilian oil company, one of the clients this group was helping them resolve issues related to data
entry. Operations of a petroleum company are large, and a large number of data transactions were
to be processed on a daily basis. They approached the group to devise a graphical front end that
would help eliminate errors in data entry, especially when working with legacy code from fixed-format
files.
TeCGraf looked at the whole series of screens that were provided to them and tried to find some
form of uniformity to help find a solution. For this they came up with a simple and unified data entry
language (DEL), which was used to describe the data in each data entry task. I think a good parallel
would be that of XML, but without the multitude of tags that make it confusing to understand. That
way one could define the entities and the restrictions or rules. This became very popular, as it was
easy to define entities and create records that would help validate the data.
With popularity came feature requests, so the users that were using DEL now required more
functionality, which was pushing DEL from being a descriptive language to a programming language
with requests such as loops, conditional control, and so on. If you were a software developer in
the ’90s, you will realize that one of the aspects that many developers spent time on was changing
the color and font of the data entry screens. The group created another specialized description
language that allowed for setting these attributes. This was called Simple Object Language (SOL), as
it allowed the user to create an object and manipulate the color, font, and other characteristics of the
object. (Sol also means sun in Portuguese.)
The architecture of this language was made more like that of a compile-and-run-type of language
than that of an IDE-type application. The API was implemented as a C library and linked to the
main program. Each type could have a callback function that functioned as the constructor (i.e., the
function is called when an object of a particular type is created). In 1993, the creators realized that
DEL and SOL could both be combined into a single more powerful language. This led to a proper
programming language that would have it all: assignment, control structures, subroutines, functions,
and so on. However, it would also work with the basic requirement to be able to offer data-description
facilities like those of DEL or SOL. They wanted it to be an easy–to-use language without cryptic syntax
and semantics, as the end users weren’t expected to be professional programmers. Lastly, they
wanted it to be portable to run on any and every platform (if required).
Because it was a modified version of SOL, the creators called this new program Lua (which mean
moon in Portuguese).
Lua Timeline
As of this writing, Lua is in version 5.2.1. It has undergone quite a few changes and has been used
extensively in many projects for enterprise, entertainment, games, and apps. For many of us, it might
come as a surprise that Lua is used in South American homes practically on a daily basis. It powers
their interactive televisions. Universities use Lua in their research to allow for quick processing and
results.
In 1996, Lua got exposure internationally after an article in Dr. Dobbs. Following the article, there
were e-mails from developers. In a paper, Roberto narrates about how Bret Mogilefsky, who was
CHAPTER 1: Introduction to Lua 3
An application is made up of all the resources graphics, music, text, etc.), which are compiled into
the application, with the Lua code along with the framework stub. When run, the framework or the
engine creates an OpenGL surface on which all of the graphics are displayed. This is how all of
the frameworks work, and this is how they can offer cross-platform compatibility. The limitations on the
framework are imposed mainly due to either the limitations of OpenGL or the framework engine.
the lead programmer at LucasArts (of Grim Fandango fame), wanted to replace their scripting
language SCUMM with Lua. This drew interest from other developers, and Lua started to appear on
newsgroups.
Starting with Lua
One important point that I’ll make throughout the book is that, with Lua, it doesn’t matter what
framework you use; what’s important is the glue that holds it all together: Lua. In the ’90s, Microsoft
was pushing client-server and three-tier architecture (similar to what Apple has been pushing as
MVC [Model-View-Controller]). The idea behind MVC is that it involves three distinct portions: a
model, which takes care of the data; a view, which displays the data from the model and provides
interaction with the user; and a controller, which communicates between the model and the view,
as these two do not have any idea of each other’s existence. The controller is the broker that helps
the two talk to each other. The most usual way to work with MVC is to use a framework, which takes
care of a lot of the details for you.
In this book, I shall cover a few frameworks: CoronaSDK, Gideros Studio, Moai, Codea, and LÖVE.
All of these except LÖVE help develop and run apps on the iOS platform. The architecture of a
Lua-based mobile app is simple, as the diagram in Figure 1-1 shows.
Figure 1-1. The architecture of an app using Lua on a mobile device platform
CHAPTER 1: Introduction to Lua
4
The MVC pattern discussed earlier holds true in this architecture. If we write our code with this in
mind, we can create not only cross-platform applications, but cross-framework ones. The controller
code that we write in Lua will change to cater for the other framework, but the rest of the code will
be the same.
In the next section, we shall focus on Lua and how to use it. After that, we’ll look specifically at the
frameworks and integrate some of the things that you’ve learned.
Setting Up Lua
If we need to work with Lua, we need to have Lua. Since most of the frameworks use Lua 5.1.4, we
shall use that version for compatibility. Lua can be obtained as a precompiled binary or source code
that you can compile. It is also available for a variety of platforms, including Windows, Mac, *nix,
iOS, and Android.
Online Lua Shell
This is perhaps the easiest way to test out the Lua code, and involves no installation or setup of any
kind. You can simply navigate to www.lua.org/demo.html.
Windows, Mac OS X, and *nix
You can download the binaries for Lua version 5.1.4 from
http://sourceforge.net/projects/luabinaries/files/5.1.4/Executables/.
You can choose lua5 1 4 Win32 bin.zip or lua 5 1 4 Win64 bin.zip as per your version of Windows.
For the Mac, there are versions for Tiger, Leopard, Snow Leopard, and Lion.
For *nix, they are based on the kernel version; in this case, it’s easier to download Lua from the app
catalog in each of the distributions.
iOS
There are two apps that I know of that allow for running Lua code interactively. Unlike the other Lua
offerings mentioned, these are not free.
 iLuaBox: This app uses the newer version of Lua 5.2 and costs about $2.99 in
the App Store.
 Lua Console: This app works with Lua 5.1.4 and costs $1.99 in the App Store.
Of the two, iLuaBox has some advanced functionality in terms of managing files and directories.
Features of Lua
Lua is implemented as a library written in C. It does not have a main program, as there is no need to
invoke something automatically; it works as in embedded mode and calls the embedding program.
This code can invoke other functions, assign variables, and read and write the data. Having been
written in C, it can also be extended; however, the official release will only add features that have
been approved by a committee.
CHAPTER 1: Introduction to Lua 5
Variables
In simple computing terminology, a variable is a location that holds a value and can be accessed by
giving it a name. Think of it as a filing cabinet in a company’s HR department. It can hold many files
with details on the employees. When you need to access data from one of them, you can look it up
via the file’s name tag. If you have two employees with the same first and last names, there need to
be two files and the name tag would require some form of identification to distinguish between the
two. Just as you cannot have two files with the same tag, you cannot have two variables with the
same name. There has to be some point of differentiation (e.g., tag1 and tag2 instead of just tag).
The names given to the variables can be a series of letters, digits, and underscores; however, they
cannot begin with a digit. The names are case sensitive, so there is a difference between T and t.
In addition to variables, Lua also uses keywords, which cannot be used for variable names, as Lua
identifies them as commands for the code, not variable names. Here’s the list of system keywords,
which cannot be used as variable names):
and
break
do
else
elseif
end
false
for
function
if
in
local
nil
not
or
repeat
return
then
true
until
while
CHAPTER 1: Introduction to Lua
6
Hello World, the Variable Way
To begin with, we need to start Lua in interactive mode for the purpose of running all of our code.
The way it works is to open a terminal in Mac OS X or *nix, type lua, and press Enter. After doing
this, you should see the screen shown in Figure 1-2. Under Windows, you can start the Lua console
from the Start menu.
Note In this book, most of the screenshots and references will be for the Mac OS X version.
Figure 1-2. The Lua interactive shell running in the terminal on a Mac
Theon the line is the prompt where you can type the Lua code you want to run. We shall start with
writing a simple Hello World example. Type the following at the prompt:
print (Hello World)
You should see the text “Hello World” printed on the next line. The print function is used to display
the text in the terminal. Let's take this a step further:
CHAPTER 1: Introduction to Lua 7
message = Hello World
print(message)
What we have just done here is assign the string Hello World to the message variable; then we use
the print function to display the value of message in the terminal.
Just like strings, we can also print numbers, and the simplest way to do so is
print(5)
age = 1
print(age)
print(Age :, age)
print(1,2,3,4,5,One)
The aim of this is to demonstrate that using print, we can display variables, numbers, and strings to
the terminal.
Strings
Strings in Lua can be enclosed in single or double quotes. So, for example, both 'Lua' and Lua
are valid. Literal strings can be used in a manner similar to C by preceding them with a blackslash
() and enclosing them in the single or double quotes. These can be used to include commonly used
escape sequences such as b, t, v, r, n, , ', and . They can also be used to specify a
numeric value with the format ddd, where d is a digit.
print(65)
There are times when you want to include chunks of text, and keeping track of the quotation marks
can sometimes get a bit tricky, especially when trying to get them to match and line up. In such
cases, you can use the long-bracket format, by which you enclose the text within [[ and ]]. Here’s
an example:
message = [[That's Jack O'Neill, with two ll's]]
If you used single quotes for enclosure in a scenario like this, you would get an error:
message = 'That's Jack O'Neill, with two ll's'
Likewise, you would also get an error using the following line, as the single and double quotes need
to have a matching pair or be escaped.
message = That's Jack O'Neill, with two ll's
The correct way to declare the same would be to place a backslash before the literal quotes, like this:
message = 'That's Jack O'Neill, with two ll's'
or like this:
message = That's Jack O'Neill, with two ll's
CHAPTER 1: Introduction to Lua
8
You will notice that it is easy to miss that, in which case the interpreter will only spawn errors. In such
cases, using the long brackets is very helpful.
Lua also has levels of nesting with long brackets; you can have various levels by inserting an equal
sign between the two opening brackets and one between the two closing brackets, like so:
testmsg = [=[ One ]=]
print(testmsg)
You can use this for some very interesting-looking source code where you can use
testmsg = [======[ One ]======]
print(testmsg) -- Prints One
Numerals
Numbers can be expressed in Lua as decimals, floats, hexadecimals, and scientific notations. Here’s
an example of each:
print(5) -- 5 This is a decimal number
print(5.3) -- 5.3 This is a floating point number
print(5.31e-2) -- 0.0531 This is a scientific notation number
print(0xfeed) -- 65261 This is a hexadecimal number
Values and Types
In languages like C, you have to define a variable with a particular type. For example, you might
need define a variable i as an integer (int), like so:
int i;
With Lua, you do not have to define the type of variable; you can simply assign the value, and the
value can change on the fly. In Visual Basic 6 (not to be confused with Visual Basic.NET), this type of
variable was called a variant variable, and had to be explicitly defined as follows:
dim i as variant
In contrast, Lua stores variables in memory. Lua stores a variable’s value and type together.
All variables in Lua are first-class values. This simply means that these values can be stored in
variables, passed to other functions as arguments, and returned from a function.
There are eight different types of variables in Lua, which I’ll describe next.
nil
This is the same as null. If you have a variable that holds a reference to the last-held value and
the garbage collector doesn’t clean it up, you can set the variable to nil to indicate that the space
referenced can be garbage collected.
CHAPTER 1: Introduction to Lua 9
boolean
boolean variables are our trusty true and false. These are used to check for conditions; however, it
should be noted that both nil and false will result in the condition being false and any other value
resulting in true.
trusted = false
if (trusted) then print(Yes) end -- Nothing is printed
trusted = 1
if (trusted) then print(Yes) end -- Yes is printed
trusted = nil
if (trusted) then print(Yes) end -- Nothing is printed
number
number variables are numbers that can be expressed as decimals, longs, integers, hexadecimals, and
floats. Lua saves the numbers as double-precision floating-point numbers.
string
Lua strings are generally 8-bit clean strings (i.e., they can hold any 8-bit character, including
embedded zeros). Unicode variables are a slightly different matter, but are handled by Lua if the
platform supports Unicode.
function
In Lua, functions can also be stored and passed as variables. This functionality of being able to store
and pass functions as parameters makes the functions in Lua “first-class functions.”
userdata
This is a memory block that is allocated from C, allowing C functions to store and access data.
userdata variables cannot be created or manipulated in Lua, but only through the C API.
thread
This is a special type of variable; this specifies an independent thread of execution. This is not the
same as the operating system thread.
table
table variables are what we would call arrays, associative arrays, hash tables, sets, records, lists,
trees, and even objects in Lua.
Note Tables, functions, and threads do not really hold any values—only references to them.
CHAPTER 1: Introduction to Lua
10
Code Blocks and Scopes
In Lua, every variable has a scope, which means that it is accessible to the code depending on its
life cycle as determined by the scope. Variables are either global or local. By default, variables are
defined as global unless explicitly defined as local.
In code, variables set between a do and an end block are not accessible outside of the block, and
any local variables that are set outside of the block are accessible inside the block.
Let us look at this with an example:
i = 1
print(i = , i)
do
local i = 2
print(i = , i)
end
print(i = , i)
Coercion is a simple term given to the process of converting a string into a number following the
conversion rules (if possible) to provide arithmetic operations between a string and a number.
one = 1
two = 2
print(one + two) -- 3 is printed
In many languages, attempting such an arithmetic operation between two different data types (in this
case a string and a number) would fail. In some other scripting languages, this code would instead
add the value to the string, resulting in the string 12. However, in Lua, this outputs the value 3,
where one is converted into numeric 1 and then added to the value of two to output 3.
However, if we wanted to add the two strings 1 and 2 to get 12, then we would need to
use what is called concatenation. In Lua the concatenation operator is the double-dot (..). This
combines the two strings and returns a new string that contains the two strings passed.
Lua Operators
The operators in Lua can be grouped into different types of operators, which include arithmetic, relational,
and logical operators, among others.
Arithmetic Operators
These do not need much of an introduction; they are simple and straightforward. Table 1-1 lists them.
CHAPTER 1: Introduction to Lua 11
Relational Operators
These are the operators used for comparing or conditions. They’re listed in Table 1-2.
Table 1-1. Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
^ Exponent
- Unary negation
Table 1-2. Relational Operators
Operator Description
== Equality (to check for equality between two values)
~= Not equal to (the opposite of equality)
 Less than
 Greater than
= Less than or equal to
= Greater than or equal to
These operators will always result in a true or a false return value. It should be noted that when
comparing two numbers or values, use the == where as a single=in Lua signifies assignment.
Logical Operators
The logical operators in Lua are
and
or
not
The way the and and or work in Lua is by what’s called the shortcut evaluation. It checks for a value,
and checks further only if it is required. and returns the first arguments if the value is false or nil; if it
isn’t, then it returns the second argument. or, on the other hand, returns the first value if the result is
not false or nil, and returns the second argument if the first argument is false or nil.
The best use of or is in functions for assigning default values:
a = a or 5 -- Can be used to assign the value of 5 if the value of a is nil or false
CHAPTER 1: Introduction to Lua
12
We can test how these work as follows:
testing = nil
print(testing)
print(testing and 5)
print(testing or 5)
print(not testing)
testing = 15
print(testing)
print(testing and 5)
print(testing or 5)
print(not testing)
Other Operators
Apart from the standard operators that we have discussed, there are a couple of other operators
offered to us by Lua. They are used for operations like concatenation and obtaining the length of
something; these two work with strings, though the # operator can also be used with arrays.
Concatenation operator:
 ..
Length operator:
 #
As mentioned previously, the concatenation operator in Lua is the double-dot (..). It is used to add
two strings together, like so:
print(one, two,  ..  buckle my shoe)
The length operator returns the length of the string.
print(#this is a long string) -- prints 21 as the length of the string
Summary
The portability of Lua means that we can run our code on various devices and desktops. The small
footprint of Lua and a very flexible and forgiving syntax allows for rapid prototyping and code testing.
We have seen that Lua is increasing in popularity with game developers. In the next chapter, we shall
take a closer look at the standard Lua libraries that provide all the commands that make up standard Lua.
13
Chapter 2
Lua Libraries
In the previous chapter, you learned the reasons behind Lua and that Lua is, after all, made up of
C code libraries. One of the advantages that the developers of Lua got from this architecture for Lua
was that they could add functionality as required. Adding functionality involved writing new functions
and making them available in Lua. It is quite a surprise that Lua does not have multiple distributions
and remains as intended by the developers; there are not many modified versions. However, many
developmental studios do modify, or rather adapt and customize, Lua for their own editors and tools.
In this chapter, we shall look at the standard Lua libraries and namespaces that provide us with their
functions. Then we’ll have a detailed look at the system- and table-related functions.
Basic Functions
Lua has some basic functions that are part of the Lua system, we’ll have a look at the following
subsections. These form part of the core library and are generally available to most of the
distributions.
assert ( v [, message] )
This function is similar to the assert function used with C; it returns an error if the value of the
argument v is false (either nil or false);. The message, if present, is displayed as an error; if absent,
the default text “assertion failed!” is displayed.
assert(money0,you need to have some money to buy something)
collectgarbage ( [opt [,arg]] )
This function is a generic interface to the garbagecollector. The function acts differently depending
on the parameter opt. The options that you can pass to this function as opt are
CHAPTER 2: Lua Libraries
14
 collect: Performs a full garbage-collection cycle. This is the default option.
 stop: Stops the garbage collector.
 restart: Restarts the garbage collector.
 count: Returns the total memory in use by Lua.
 step: Performs a garbage-collection step. The step size is governed by arg.
 setpause: Sets arg as the new value for pause and returns the previous value of
pause.
 setstepmul: Sets arg as the new value for the step multiplier and returns the
previous value for step.
Tip If you want to know the memory usage of your app and clear up the memory and objects, you can
force the garbagecollector to free up and reclaim the memory allocated and then print the amount
of memory used after a cleanup by using the print(collectgarbage(count)) command.
dofile ( [filename] )
You saw in Chapter 1 that Lua executes the code in chunks. This function opens the named file and
executes its contents as a Lua chunk. When called with no arguments, it executes the contents from
the standard input (stdin). It returns all values returned by the chunk. stdin is not available on iOS
devices, and with CoronaSDK the function is sandboxed (i.e., disallowed).
dofile(somefile.lua)
error ( message [,level] )
This function terminates the last protected function and returns the message as the error message.
error(This operations is invalid)
_G
This is not exactly a function, but a global variable. Lua does not use this variable, but it holds all the
global variables and function.
getfenv ( [f] )
This function returns the current environment in use by the function. The function f can be a Lua
function or number.
CHAPTER 2: Lua Libraries 15
getmetatable ( object )
This function retrieves the metatable associated with the object. It returns nil if there is no metatable
present. This is mostly used to add functionality to an object table. In some cases, this is also used
as a signature of the object. So while the type function does not tell you much, the metatables can
be compared with a list of known metatable signatures to get more information.
ipairs ( t )
This function returns a function that returns three values, an iterator function, the table t and 0. It
works with the array tables only. The following code will iterate over the pairs up to the first integer
key missing from the table:
t = {1,2,3,4,test = test,5,6}
t[3] = nil
for i,v in ipairs(t) do
-- body
print(i,v)
end
load ( func [,chunkname] )
This function is similar to the dofile command; it loads a chunk using the function func. Each
time the function is called, the function must return a string that concatenates with the previous
result. When the chunk is complete, it returns nil and an error message. The chunkname is used for
debugging. When the function is called and an error occurs, Lua displays debugging information,
including the line number where the error occurred and the name of the Lua file in which the error
occurred. When we have compiled chunks, there is no filename and hence, for debugging purposes,
it is up to you, the developer, to provide that information in the form of the chunkname parameter.
loadstring ( string [,chunkname] )
This function is similar to load, but instead of loading the compiled bytecode from a file, it takes the
compiled code (chunk) from a string.
loadstring(compiledChunk, OurChunk)
next ( table [,index] )
This function allows the program to iterate through all the fields of a table. The function returns
multiple values. Internally, the function takes on system commands.
t = {One, Deux, Drei, Quarto}
print(next(t, 3))
CHAPTER 2: Lua Libraries
16
pairs ( t )
This function is used to iterate through the keys and values in a table.
t = {one=Eins,two=Zwei, three=Drei}
for k,v in pairs(t) do
-- body
print(k,v)
end
pcall ( f, arg1, … )
This function calls the function f with the arguments in protected mode. This means that any errors
inside of the function f are not propagated outside of the function.
print( … )
This function is the one that you will use most during development. It can receive any number of
arguments, and it prints all of their values to stdout. It uses tostring and tonumber for conversion,
and it provides an easy way to show a value quickly. However, it is not intended for formatted output.
rawequal ( v1, v2 )
This function is used to check if the value v1 is equal to v2. It returns a Boolean indicating the outcome
of the comparison.
rawget ( table, index )
This function returns the value of table[index] without invoking any metamethod. The table must be
a valid table and the index a non-nil value. This is equivalent to
table[index]
rawest ( table, index, value )
This function sets the value of table[index] without invoking any metamethods. The table must be a
valid table and the index a non-nil value. This is equivalent to
table[index] = value
select ( index, … )
This function returns all of the arguments passed to the function starting with the argument after the index
specified.
CHAPTER 2: Lua Libraries 17
setfenv ( f, table )
This function sets the environment to be given to the function f. f can be a Lua function or a number
that specifies the value of the platform.
setmetatable ( table, metatable )
This function is used to set the metatable for any table.
tonumber( e [,base] )
This function is used for converting between the numbers from string to numerical values. If the
argument e is in a form that can be converted, it is converted and returned; otherwise, nil is
returned.
print( tonumber(42) )
print( tonumber(2A,16))
tostring ( e )
This function tries to convert the given argument to string format. If the passed parameter is a
number, it is converted into a string. If it is an object and its metatable has a tostring function, the
tostring function is called to convert the passed parameter.
Note Lua converts between numbers and strings as required (and if possible). However, calling the
tostring function is a way to tell Lua to convert the value into a string. Objects and tables are not
automatically converted into strings; instead, the function tostring (if present) is called, which returns
the string representation of the object/table.
type ( v )
This function returns the type of the arguments, coded as a string. The possible results are nil,
number, string, boolean, table, thread, and userdata.
print(type(Hello World))
print(type(4))
print(type({}))
unpack ( list [, i [, j] ] )
This function returns the elements from an array table. This function is equivalent to
return list[i], list[i+1], ... , list[j]
CHAPTER 2: Lua Libraries
18
Manually, this code can only be written for a fixed number of elements, and we cannot use a loop,
as we have values to return. The parameter i specifies the start element and j specifies the last
element, by default. (When these values are not provided, i is 1 and j is the length of the list as
defined by the # operator.)
local color = {255,255,255}
function tableToParams(theTable)
return unpack( theTable)
end
print( tableToParams(color))
_VERSION
This is not a function, but a global variable. This holds the current interpreter version.
print ( VERSION ) -- This will return the version of Lua in use
xpcall ( f, err )
This function is similar to the pcall function, except that with this call, you can specify a new error
handler. If there is an error inside of the function f, it is not propagated, and xpcall catches the error
and in turn calls the err function with the original error object
function spawnError()
-- this function shall spawn an error
local this=someFunctionNotDeclared()
end
print(xpcall(spawnError, function(err) print(Error:, err) return 1 end))
System Libraries
The commonly bundled system libraries that you will end up using while working with Lua are
 table
 string
 math
 file
 os
The table namespace provides us with the functions related to array manipulation, as these
functions are not applicable to hash arrays or associative arrays. This is explained in detail in the
following section.
The string namespace provides us with functions to deal with string manipulation. These allow
for searching, splitting, and replacing strings, and are quite helpful for parsing and displaying
information. We shall have a close look at the string namespace in Chapter 5.
CHAPTER 2: Lua Libraries 19
The math namespace provides all the math-related functions; these are the basis for all the logic in
most games. The math namespace provides all math-related functions that can help calculate things
like where the player is, where the objects are, whether the player won or lost, and much more. We
shall look at this namespace in detail in Chapter 4.
The file namespace, covered in Chapter 3, provides file-related functions, including those that
allow the user to read, write, and delete files. Note that file operations do not include much file
system–related functionality, and there is a third-party library called Lua File System (LFS) that offers
the missing functionality.
The os namespace provides functions that are related to OS-specific functions, including functions
that deal with things like time, date, and locale. We shall look into this further ahead in the “OS
Functions” section of this chapter.
The way to use these libraries is to prefix the library name followed by a dot and the function. This
is a good way of separating the functionality available in the library from the common or global
area. With libraries, variables and functions can be part of the namespace. For example, if we had a
function a1, and the namespace myFunc had a function defined as a1, these two would be completely
different functions. To access these functions, simply add the namespace as a prefix in front of the
function name, as follows:
-- call the global a1 function
a1()
-- calling the a1 function available in the namespace myFunc
myFunc.a1()
Note There is no function called a1, so these commands will not work; these are just for illustration purposes.
Table Functions
You may have already noticed that in Lua, if anything is not a string or a number, then it is an object
(i.e., a table). Tables are the most important data type in Lua. There are a handful of functions to
manipulate end work with the tables. These are useful functions for working with array-type tables.
The functions available are described in the following subsections.
table.concat ( aTable [,sep [,i [,j] ] ] )
This function returns the elements of an array (if they are either strings or numbers) concatenated as
a string. These are separated by a separator, as indicated by sep, which is a blank string by default.
If no parameters are passed for i and j, then i is the first element and j is the length of the table.
If i is larger than j, then an empty string is returned.
If you were to write this function yourself, it would look like
return aTable[i]..sep..aTable[i+1] ... sep..aTable[j].
local aryTable = {1, deux, 3, vier, 5}
print( table.concat( aryTable, ,, 1,3))
print(table.concat(aryTable))
CHAPTER 2: Lua Libraries
20
table.insert ( aTable, [pos,] value )
This function is used to insert a value into the array table, as indicated by aTable. The value is
inserted at the position indicated by pos; if no value is indicated for pos, then it is assigned the
default value of the length of the table plus 1 (i.e., at the end of the table).
local aryTable = {1, 3, 4, 5}
table.insert(aryTable, 2, 2)
print(table.concat(aryTable, ,)
table.insert(aryTable, 6)
print(table.concat(aryTable, ,)
table.maxn ( aTable )
This function returns the largest positive numerical index of the given array table. Remember from
Chapter 1 that the # operator returns the length of an array, but only of a contiguous section. So, if
in a program you added values to the indices in a nonserial manner (i.e., not continuous), then the #
operator would return the length as the block that was continuous. table.maxn, on the other hand,
iterates through all the elements and returns the largest numerical index.
local aryTable = {1,2,3,4,5}
print(#aryTable, table.maxn(aryTable))
aryTable[10]=10
print(#aryTable, table.maxn(aryTable))
aryTable[25]=25
print(#aryTable, table.maxn(aryTable))
table.remove ( aTable [, pos] )
This function is like insert, but with the difference that it removes an element from the array table and
returns the element being removed. In both insert and remove, the elements are shifted to accommodate
the new index as required. The default position for pos is the length of the table (i.e., the last element).
local aryTable = {1, 2, 3, 4, 5}
table.remove(aryTable, 2, 2)
print(table.concat(aryTable, ,)
table.remove(aryTable)
print(table.concat(aryTable, ,)
print(aryTable[3])
table.sort ( aTable [, comp] )
This function is very useful when working with a series of values that need to be sorted. When no
comp is specified, it uses the standardLua operator to compare two values, which works fine with
numeric values. However, there could be situations where you might need to sort multidimensional
arrays or arrays that contain non-numeric data. For such cases, the comp function is used. comp
receives two table elements and returns true when the first is less than the second.
CHAPTER 2: Lua Libraries 21
local aryTable = {4,7,1,3,8,6,5,2}
print(table.concat(aryTable, ,))
table.sort(aryTable)
print(table.concat(aryTable, ,))
Note These functions can be used only with array-type tables and are available in the table namespace.
In order to use these functions, you need to prefix them with table.
OS Functions
There are a few functions that are available to interact with the OS; these can be found in the os
namespace and hence are prefixed with os. The following subsections describe how they’re used.
os.clock ( )
This function returns the approximate CPU time used by the program, in seconds. Every time some
code is executed, this is incremented with the amount of CPU time used by the code.
print(os.clock()) --0.030148 (could be different on your system)
print(os.clock()) --0.030250 (could be different on your system)
Note This does not return the time from the system clock; this is just the total CPU time used.
os.date ( [format [,time] ] )
This function returns a string or a table containing the date and time, formatted as specified by the
given string format. If no parameters are passed, it returns the string containing the current date and
time based on the host system and the current locale. If the format is *t, then the function returns
a table with the following fields:
 year (four digits)
 month (1–12)
 day (1–31)
 hour (0–23)
 min (0–60)
 sec (0–60)
 wday (1–7, beginning with Sunday)
 yday (day of the year; 1–366)
 isdst (Boolean indicating if daylight saving time is in effect)
CHAPTER 2: Lua Libraries
22
os.difftime ( t2, t1 )
This function returns the difference in the number of seconds between t2 and t1.
os.execute ( [command] )
This function is the equivalent of the C system command. It executes the command passed in
the OS shell. It also returns the status code, which is very much system dependent. This is not
applicable on iOS, as it would be sandboxed and not execute.
os.exit ( )
This function calls the C function exit, which terminates the application. Though this works on iOS
devices, it should not be used. Any app that exits in this manner is considered to be an app that has
crashed. The only way to exit an app should be when the user explicitly presses the Home button to
exit the app. You can run the risk of Apple rejecting your application if it uses this function. Having
said that, there are a couple of apps that have managed to slip under the Apple radar and exit an
app in this manner (and the experience is indeed that of when an app crashes).
os.getenv ( varname )
This is not applicable on iOS devices.
os.remove ( filename )
This function deletes a filename or directory with the given name. The directories are removed if they
are empty. If the function fails, it returns nil and a string describing the error. This will work only on
the directories and files that you can work with (i.e., the ones in the Documents directory on an iOS
device). The other directories are sandboxed and unavailable.
os.rename ( oldname, newname )
This function renames a file or directory with the given oldname to the newname. If the function fails, it
returns nil and a string describing the error. This works only with files in the Documents directory.
Note The reason this works with files in the Documents directory is that most of the other directories
are sandboxed or restricted from use. Any command that tries accessing the restricted directories will
fail and do nothing.
os.setlocale ( locale [,category] )
This function is not available in the context of iOS devices.
CHAPTER 2: Lua Libraries 23
os.time ( [table] )
This function returns the current time when called without arguments. The table passed as
parameters should have the fields set to at least year, month, and day. Other fields, such as hour,
min, sec, and idist, are optional.
os.tmpname ( )
This function returns a string with a filename that can be used for a temporary file. This file needs to
be explicitly opened and explicitly removed when not required. This is different from an io.tmpfile
function (discussed in the next chapter), which automatically removes the file when the program ends.
Tables: A Quick Overview
I have noted that tables are one of the many types of variables available in Lua. Though it might
sound trivial, tables are the backbone of Lua, and they’re used in many ways: as arrays, hash tables
(associative arrays), and objects, and in plenty more. The following subsections will discuss tables
as arrays and hash tables.
Tables As Arrays
The Lua equivalent of an array is a table. All arrays in Lua have an index base of 1, which means that
the first entry starts at 1 (not 0, as in many other languages). Arrays need to have a numeric index.
These can be multidimensional and do not need to be dimensioned at declaration. These can grow
and be redimensioned at runtime.
local theArray = {}
for i = 1, 10 do
theArray[i] = item . . i
end
Tables As Associative Arrays
Tables are the Lua equivalent of associative arrays, hash tables, and even NSDictionary objects. The
difference between an array and an associative array is that, instead of having a numeric index to
access an element of the array table, an associative array can use a string to access the elements.
local theTable = {}
for i = 1, 10 do
theTable[item..i] = i
end
Note Lua is very flexible and hence is very forgiving, even if you mix the two types of arrays.
CHAPTER 2: Lua Libraries
24
local theMixedTable = {}
for i = 1, 5 do
theMixedTable[i] = item .. i
end
theMixedTable[name] = mixedTable
theMixedTable[subject] = coding
print(theMixedTable.name, theMixedTable[3])
Functions: An Advanced Look
In the previous chapter we had a look at functions and how Lua sees them. Lua objects and
structures are Lua tables, and the good part is that tables can hold functions and other tables,
string, and numbers. In effect each object with a function is like a namespace that has its own set
of functions. To access the function of a particular object, you need to access the function with the
namespace prefixed.
myObj = {
type = furry,
name = Furry 1,
description = Fluffy furry teddybear,
display = function ()
print(description)
end
}
myObj.show = function()
print(Now Showing...)
end
To call the function, you use the following:
myObj.display()
myObj.show()
Tables As Objects
As you’ve seen, tables can be used as objects. In this next example, we’ll create an object called
myObj that has properties of type, name, description, and so on. In this example, you’ll create a game
that spawns a series of animals, each with different strengths and different functions for movement.
Since some of the functions might overlap, in order to avoid writing the same code over and over
again, you’ll create a new object based on the parent object, such that all of the functions are
available to this object. (We shall create such objects later in the book.) So, when this object is
passed, you can simply invoke the move function that is common to the animals, but might be
specific to each of the animals depending on its type.
CHAPTER 2: Lua Libraries 25
One way to manage this is as follows:
local cat 01 = animal.new(cat)
local mouse 01 = animal.new(mouse)
animal.move(cat 01)
animal.move(mouse 01)
This might work for some; however, an alternative method to manage this would be the following:
local cat 01 = animal.new(cat)
local mouse 01 = animal.new(mouse)
cat 01:move()
mouse 01:move()
Further, if you had this in an array of animals, you could just about as easily have something like this:
local i
for i=1,#aryAnimals do
aryAnimals[i]:move()
end
Or you could very well also use something like
aryAnimals[i].move(aryAnimals[i])
Notice here how the function is invoked using the dot (.) or the colon (:). This is something a lot
of beginning Lua developers come across, and they often have questions about the difference
between, say, cat 01:move() and cat 01.move(). The following section will describe the differences.
The Difference Between . and :
In the preceding example, there’s no difference between calling cat 01.move() and cat 01:move().
But let’s consider that in the same function we also need to pass a parameter speed, which indicates
how fast the animal should move. So we simply pass the speed as a parameter as
cat 01:move(10)
or
cat 01.move(10)
This on the face of things seems right, but will produce two very different results. The reason is that
when we use the ., we are telling Lua to invoke the function that is a member of the object (table),
and when we use the :, we are telling Lua to do this and we’re also passing the function an unseen
parameter of itself. So when we call the function with :, we are passing it two parameters: the first
being the object itself and the second being the speed. With the . method, on the other hand, we
pass it only one, which is the speed. Let’s look at how it is defined in code (see Figure 2-1).
CHAPTER 2: Lua Libraries
26
Notice that the functions are declared differently, but the output of both is the same. In short, you
can say that obj:func() is the same as calling obj.func(obj).
Figure 2-1. The output of the function in Lua running in the terminal
Note It is very easy to forget about the way you might have declared the function and hence end
up calling it a different way, which can cause some hiccups in your code where a parameter passed
would get shifted and give you strange results. To avoid that, keep a consistent method of declaring and
calling functions.
From that last example, one question that might come to mind is, When do you use a single dot
(.) and when do you use a colon (:) if Lua is not an object-oriented language? Why would you ever
need that? In order to answer these questions, let’s work on an object and give it some functionality.
This sample doesn’t use objects or external files, so it can be run in the Lua interactive console
without any problems.
CHAPTER 2: Lua Libraries 27
function newAnimal(name)
local animal = {
name = unknown,
says = pffft,
position = {x = 0,y = 0},
}
animal.name = name
if name==cat then
animal.says = meow
elseif name==dog then
animal.says = bow wow
elseif name==mouse then
animal.says = squeak
end
function animal:speak()
print(animal.says)
end
function animal:move(speed)
animal.position.x = animal.position.x+speed
end
return animal
end
Now we can create a new instance of an animal by simply calling
cat 01 = animal.new(cat)
cat 01:speak()
This is perfectly fine as an example that creates a new object every time it is invoked. However, this
is also how many beginners would code—note that in the functions, while we are passing the object
via self, we are not using it, and we are still referencing it by the fixed animal table that we created.
This can cause a bit of grief later on if it’s not checked right at the start. The way to avoid this being
a problem in the future is to replace the namespace with the object referenced as self instead.
The modified code would look like the following:
function newAnimal(name)
local animal = {
name = unknown,
says = pffft,
position = {x = 0,y = 0},
}
animal.name = name
if name==cat then
animal.says = meow
elseif name==dog then
animal.says = bow wow
elseif name==mouse then
animal.says = squeak
end
CHAPTER 2: Lua Libraries
28
function animal:speak()
print(self.says)
end
function animal:move(speed)
self.position.x = self.position.x+speed
end
return animal
end
This would work fine and not cause issues.
cat 01 = animal.new(cat)
cat 01:speak()
cat 02 = animal.new(dog)
cat 02:speak()
When we run the code, the functions get the object passed rather than the Animal namespace. This
also ensures that the variables that are modified are specific to the object rather than the ones in the
Animal namespace. That will thereby eliminate the issues mentioned earlier.
Summary
This chapter focused on functions and tables, the building blocks of Lua programming. It’s important
to remember that everything that is not a string, a number of boolean is a Table. Tables are very
powerful and important in Lua. You’ll be reading a lot about them (in some form or other) in most of
the chapters.
Another important concept that we touched upon is the namespace. Namespaces help to
distinguish between the functions available in the main namespace (the global functions) and the
functions in a custom library.
29
Chapter 3
File Operations
When creating an app or a game, you need file I/O (input/output). You may not be working with
a database, but there will always be the need to save something back to the disk; it could be the
levels, the high score, a character the player might have unlocked, or some information regarding
in-app purchases.
So, let’s first look at what we have available in terms of functions that offer file operation functionality.
Lua has two sets of functions for file operations, one called implicit and the other explicit. The
difference between the two is that implicit functions work on the default file as provided by the io
namespace, whereas explicit functions work with a file handle provided from a previous operation,
such as io.open.
Implicit Functions
This section lists and describes the implicit functions you’ll be using in your Lua programming work,
accompanied by a short example of how each is used in code.
io.close ( [file] )
This function closes the output file; it is similar to file:close(), but when no file is passed, it
closes the default output file. You can see how io.close is used to close a fileHandle. To confirm,
we print the type of fileHandle to check if the file is open or closed.
fileHandle = io.open(file.txt, w)
print(io.type(fileHandle))
fileHandle:write(Hello world)
io.close(fileHandle)
print(io.type(fileHandle))
CHAPTER 3: File Operations
30
io.flush ( )
This function runs file:flush() on the default file. When a file is in buffered mode, the data is not
written to the file immediately; it remains in the buffers and is written when the buffer nears getting
full. This function forces the buffers to write to file and clear up.
io.input ( [file] )
This function returns the current default input file when called without any parameters. The parameter
passed can be either a filename or a file handle. When the function is called with a filename, it sets
the handle to this named file as the default input file. If it is called with a file handle, it just sets the
default input file handle to this passed file handle.
io.lines ( [filename] )
This function opens a given filename in read mode and returns an iterator function that returns a new
line from the file every time it is called. When the iterator function detects that the end of the file has
been reached, it closes the file and returns nil.
When io.lines is called without a filename, it is equivalent to io.input():lines(), and it reads from
the default input file and does not close the file when the end is reached.
Here’s a way to access this function:
for line in io.lines(filename) do
print(line)
end
io.open ( filename [,mode] )
This function is the main function that you use in reading and writing files with Lua. The mode is a
string value that can be one of the following:
 r: Read mode (default).
 w: Write mode.
 a: Append mode.
 r+: Update mode. All previous data is preserved.
 w+: Update mode. All previous data is erased.
 a+: Append update mode. All previous data is preserved and writing is only
allowed at the end of the file.
The mode can also have a b at the end to indicate that the file is to be opened in binary
mode rather than in text mode. This function returns a file handle that can be used in explicit file
operations.
file = io.open(myfilename.txt, r)
CHAPTER 3: File Operations 31
io.output ( [file] )
This function is similar to io.input but operates on the default output file instead. Using this
function, you can redirect the output to the file you want. Here’s an example of how it’s used:
oldIOFile = io.output()
io.output(mynewfile.txt)
io.write(Hello world)
io:output():close()
io.output(oldIOFile)
io.read ( … )
This function is equivalent to io.input():read().
print(io.read())
io.tmpfile ( )
This function returns a handle for a temporary file; the file is opened in update mode and removed
automatically when the program ends.
fh = io.tmpfile()
fh:write(Some sample data)
fh:flush()
-- Now let's read the data we just wrote
fh:seek(set, 0)
content = fh:read(*a)
print(We got : , content)
io.type ( obj )
This function returns the result if the handle specified by obj is a valid file handle. It returns the string
file if obj is an open file handle and the string closed file if obj is a closed file handle. It
returns nil if obj is not a file handle.
print(io.type(fh)) – prints nil as fh is nil
fh = io.input()
print(io.type(fh))
io.write ( … )
This function is equivalent to io.output():write().
io.write(Hello World)
CHAPTER 3: File Operations
32
Explicit Functions
This section lists and describes the explicit functions you’ll be using in your Lua programming work.
file:close ( )
This function closes the file that is referenced by the file.
file = io.open(myFile.txt, w)
file:write(Some Data)
file:close()
file:flush ( )
This function saves any data that is not as yet written (in the buffer) to the file.
fh = io.tmpfile()
fh:write(Some sample data)
fh:flush()
file:lines ( )
This function returns an iterator function that returns a new line from the file every time it is called. It
is similar to io.lines, with the difference that this function does not close the file when the loop ends.
local file = io.open(filename)
for line in file:lines() do print(line) end
file:close()
file:read ( [format] )
This function reads data from the file according to the given format. By default, read reads the entire
next line. The formats that are available for reading are
 '*n': Reads a number; returns a number instead of a string
 '*a': Reads the whole file starting from the current position
 '*l': Reads the next line; returns nil when the current position is at the end of
the file (default format)
 number: Reads a string of characters as specified by the number, returning nil at
the end of the file.
Following are some examples of using these:
local filename = data test.txt
local file = io.open(filename)
CHAPTER 3: File Operations 33
local contents = file:read(*a)
file:close()
print(Contents of the file:, contents)
If this file were opened in binary mode and we needed to get only a particular number of characters,
then we would use it as follows:
local filename = test.zip
local file = io.open(filename,rb)
local contents = file:read(2)
file:close()
print(File Header:, contents) -- All ZIP files have the starting two characters as PK
file:seek ( [whence] [, offset] )
This functions sets and gets the current file position. whence is a string value that can be any of the
following
 'set': The base position 0 (beginning of the file)
 'cur': The current position (default value)
 'end': The end of the file
The offset value passed is measured in bytes from the base specified as per one of these three
options.
file:seek is one of most important functions when working with binary files and fixed formats; it
allows the developer to iterate back and forth to overwrite or update certain portions of the file.
fh = io.tmpfile()
fh:write(Some sample data)
fh:flush()
-- Now let's read the data we just wrote
fh:seek(set, 0)
content = fh:read(*a)
print(We got : , content)
file:setvbuf (mode [, size] )
This function sets the buffering mode for an output file. There are three buffering modes available in
Lua, and their values are passed as strings:
 'no': No buffering is set, so the output of any operation appears immediately.
 'full': Full buffering is set, so the output operation is only performed when the
buffer is full. You can force a flush to write the buffers.
 'line': Line buffering is set, so the output is buffered until a newline character
(Enter) is found.
io.output():setvbuf(no)
CHAPTER 3: File Operations
34
file:write( … )
This function writes to the file each of the arguments passed to the function. The arguments must be
either strings or numbers. To write other values, you might have to convert them to string format.
file = io.open(myfile.txt,w)
file:write(Writing to a file)
file:close()
Note The pure implementation of Lua lacks the functions and commands required for file system access.
This is generally available as an external library that can be added. It is called Lua File System (LFS).
As of this writing, you can integrate it with all frameworks (the amount of effort this takes, however,
depends on the framework.)
Uses of File I/O in Gaming
Though this is a no-brainer, there are so many reasons why you might want to read or write data
from the storage. It can be for little things like level-related data and high scores, or for complex
things like saving the state of the game with the entire inventory, units, and so on. In the game, the
onus is on you to save and load the data to help provide continuity and seamless game play to the
player.
Let’s look at how we would do that when dealing with stuff like life, health, score, level, and so forth.
Saving a Variable
In many games, you generally get only about three lives. So, consider the following code:
local lives = 3
print(You have  .. lives ..  lives left)
There are many ways of dealing with this. One good way would be to save the data as soon as you
change it—something like an autosave option. So, let’s write out lives variable to the storage so
that it persists.
function writeToFileSingle(value, filename)
local hfile = io.open(filename,w)
if hfile==nil then return end -- Did not get a handle on the file
hfile:write(value)
hfile:close()
end
In the preceding code, we declare a function called writeToFileSingle that takes two parameters:
value and filename. The function opens a file, writes the data to the file, and then closes the file.
CHAPTER 3: File Operations 35
If we open a file, we are responsible for closing it too. When we try to open a file using the io.open
function, it returns the file handle and a string that contains the reason for the failure (if it fails to open
the file).
To save our value using this function, we simply call
writeToFileSingle(score, score)
writeToFileSingle(health, health)
and so on.
Congratulations, you have now written code to save a variable, and it can be run in the interactive
Lua shell, as expected.
Note Irrespective of which platform you choose as a developer, the preceding Lua code should work
across most of the platforms and Lua frameworks.
Grabbing the Data
In addition to saving data, we also need to retrieve it. In a game, dumping data that we cannot retrieve
is as good as not saving any data at all. We have, with the earlier function writeToFileSingle, saved
our data to a variable. Now comes the tricky part: reading the values from the file.
In theory, reading the data from a file should be the reverse process of writing to the file. So, we
open the file that we have saved our data into and then we read all of the data from the file.
function readFromFileSingle(filename)
local hfile = io.open(filename, r)
if hfile==nil then return end
local value = hfile:read(*a)
hfile:close()
return value
end
Since we’ve saved our data using the writeToFileSingle function, we can retrieve our data easily,
like so:
print(readFromFileSingle(score))
print(readFromFileSingle(health))
Note Since the data is one piece of information per file, the order in which you save it and the order
in which you load it shouldn’t matter.
If the file does not have any data, it just returns nil, which pretty much means the same and can be
managed if required.
CHAPTER 3: File Operations
36
How the Code Works
It is rather easy. Most of the code is similar to what we used in writeToFileSingle, which involves
opening a file, but in read mode instead. (If you do not specify a mode while opening a file to read,
the default mode is read mode). Then we use the read function with the *a parameter to read the
entire contents of the file. This is fine for this scenario, as we only have a small amount of data to
read. Then we close the file and return the data read from the file.
Potential Issues
These two functions work well for loading and saving data. But, as mentioned, it’s not good to have
a file for each piece of data that we want to save; it would be better to have a single file than multiple
files with scraps of data in them. So, the next possible option is to save all of the data in a single file.
Doing so isn’t much different than what we did in the preceding code. The difference is that we save
multiple values to the file, like so:
function readFromFile(filename)
local results = {}
local hfile =io.open(filename)
if hfile==nil then return end
for line in hfile:lines() do
table.insert(results, line)
end
return results
end
There are a couple of differences in this code as compared to the earlier code. The first is that we
use an array table called results to store everything we read from the file. The next is that instead
of using hfile:read(*a) to read the content, we use hfile:lines() to get one line at a time from
the file. The newline character (Enter) separates the data and is the delimiter between the two lines.
Once we get this data, we store it into the array results by using the table.insert function to add
the data to the end of the table.
Once we get the array returned to us, the positioning of the data is important. The positions of the
data shall be fixed, so we need to know in advance what position coincides with what data.
Saving Data to a Variable
Here’s a quick tip on how to manipulate global variables. In Chapter 2, you read about a variable G,
which is actually a table object and holds all the global variables, functions, and so on. When we
declare a variable (without local scope), it is assigned to this table as a global variable. What we are
going to do in this quick exercise is declare a global variable, read the value of the variable, and then
manipulate it using the G table.
myVar = 1
print(myVar)
myVar = myVar + 1
print( G[myVar])
CHAPTER 3: File Operations 37
G[myVar] = G[myVar] + 1
print(myVar)
G.myVar = G.myVar + 1
print(myVar)
How the Code Works
We start our code with declaring a global variable called myVar and assigning it a value of 1, and
then we print it to the screen. Next we increment it by 1 using myVar=myVar+1. This time we print
the value again, but instead of using print(myVar), we access it directly from the global table G via
print( G[myVar]). Then we increment the variable by 1 again but using G[myVar] and print the
value using print(myVar).
Lastly, we increment the value again by 1, but this time we access it using the G.myVar method
to access the value and print the results. The idea of this exercise is to demonstrate how Lua uses
global variables and how they can be accessed using G.
Note Though global variables can be accessed in this manner, it is suggested that local variables be
used instead; this reduces the number of variables used, saves on stack memory, and also had a speed
advantage over global variables.
Back to our saving and loading of data, we want to consolidate our data into one file so that we
can read our data in one go. In our modified version, we are reading the data into an array called
results. The only issue is that to access the values, we need to access the data by the numbered
index—but how would we know what each numeric index corresponds to?
Let’s try to read the data and also set the global variables with the values.
function readFromFile(filename)
local results = {}
local hfile = io.open(filename)
if hfile==nil then return end
local lineNo = 0
for line in hFile:lines() do
table.insert(results, line)
lineNo = lineNo + 1
if lineNo == 1 then
G[score] = line
elseif lineNo == 2 then
G[lives] = line
elseif lineNo == 3 then
G[health] = line
elseif lineNo == 4 then
G[level] = line
end
end
return results
end
CHAPTER 3: File Operations
38
This is more or less what our code looked like earlier, only we have added a variable called lineNo
and we keep incrementing it based on the lines read. When lineNo is 1, we save the value we have
read into the variable score. Then we save lineNo 2 into lives, and so on, till lineNo is 4, after which
(if there are more lines) we just don’t read them.
Potential Issues
In your app, the number of variables that you might store could be different for each application.
You would never know the order in which your data is saved, and if the order of saving the data
or reading the data is changed, you might have values that end up in the wrong variables. Most
importantly, it would be near impossible to set up multiple if .. then statements to load the
variables, not to mention the names for those variables.
So what we are going to do to fix this issue is have a table with the data and field names in it. This
will provide us with the flexibility to expand this further in the future.
function readFromFile(filename,resTable)
local hfile = io.open(filename)
if hfile == nil then return
local results = {}
local a = 1
for line in hfile:lines() do
G[resTable[a]] = line
a = a + 1
end
end
We read through the data one line at a time, and with each loop, we increment the index variable a.
We store the value that we have read into a global variable with a name specified in the array.
For example, if we had specified in our array that we wanted the values to be Line1=Score,
Line2=Lives, and Line3=health, then the function will automatically create global variables with
these names and assign the value to them.
This function will now read the data, save it into the array table, and access it via the global variable.
However, we need to pass it the table that is modified for this.
local aryTable = {
Score,
Lives,
Health,
}
We call the function simply as follows:
readFromFile(datafile, aryTable)
This method has its own set of problems. What if we were to add some data in aryTable not at the
end, but in the middle? This would make the variables all mixed up and in the wrong places. So how
do we fix that? There are many easy ways to approach this issue, and each has its own set of pros
CHAPTER 3: File Operations 39
and cons. However, the best method would be to get the name of the variable and the value of the
variable from the file.
Writing Data to the File
We have written some code to read our data from the file. Now we’ll write some code to write the
data, which could be read using the preceding function.
function writeToFile(filename, resTable)
local hfile = io.open(filename, w)
if hfile == nil then return end
local i
for i=1, #resTable do
hfile:write( G[resTable[i]])
end
end
The code for writing the data to the file is not very different. We open the file in write mode, and then
we iterate through the list of variables that we want to save to the file. These are found from the
resTable parameter passed. So, whatever we have in this table, the function shall attempt to save
those variables to the file.
Saving a Table
We just saved data that is in the form of either strings or numbers. If the data to be saved is anything
else, the functions will start to fail, and more so if the variable is a table. The biggest issue with
tables is iterating through the depths of the table.
If you were to use any other programming language, you would hear, “Why not serialize the data?”
I’ll explain why this isn’t a good idea in Lua.
The mark of good developers is their ability to avoid reinventing the wheel, instead spending their
time with things that warrant their focus. Lua has a third-party Lua library that allows you to use
JSON in your Lua projects; this library can help encode or decode the information between the table
object and a JSON-encoded string, like so:
local json = require(json)
local theTable = {
title = Learn Lua for iOS game development,
author = Jayant Varma,
publisher = Apress,
eBook = true,
year = 2012,
}
local resString = json.encode(theTable)
writeToFileSingle(restring,mytable)
local readString = readFromFileSingle(mytable)
local resTable = json.decode(readString)
for k,v in pairs(resTable) do
print(k,v)
end
CHAPTER 3: File Operations
40
When you run this code, you will see that we save the data we create as a string to a file called
mytable. In the example, we read the data back and decode the JSON-encoded string to an
expanded Lua form table. Then we list the fields available in that table to prove that the code works.
Note Though this code is completely valid, if you run the code in the Lua interactive shell, you might
face issues such as error messages, as there is no json.lua file in the path.
Dynamic Variables
How do I create dynamic variables? is one of the most commonly asked question by many
developers, especially ones that are beginning their journey with development. Some beginner
developers use variables as follows:
Object1 = Apple
Object2 = Ball
Object3 = Cat
Object4 = Dog
In this code, the developer wants to create a series of such variables dynamically and be able to
access them by specifying the last digit, so the access expected would be
number = 3
print(Object .. number)
and the expectation is that it should output Cat. However, what it outputs is Object3. Most beginning
developers assume that it should have worked as expected. If you need to access the variable in
this manner, it is not by creating multiple variables. The proper way to do so is to create an array. The
array can be accessed by passing it the number as we expected to do.
Objects = {Apple, Ball, Cat, Dog}
number = 3
print(Objects[number])
This works perfectly fine for what we need. This time around we see the output Cat.
Summary
In this chapter you learned about the implicit and explicit functions relating to file I/O. You also saw
how to read and write data as singular values, and how to write an entire table of data onto the
storage space on the device. Files are good for saving scraps of data; however, when you need to
access larger amounts of data, it would be better to use a database.
In the next chapter we shall look at the math namespace, which offers functions that we can use to
do all of the calculations required for our apps.
41
Chapter 4
Math with Lua
Love it or hate it, if you have decided to be a developer, you will have to come face to face with
math. It is indeed surprising to see how many students dislike or shy away from math, but it just
comes back to us in some form or the other, irrespective of our profession. An accountant needs
to look at the accounts and add them up (requiring math), a surveyor needs to apply trigonometric
principles to get elevation and terrain information, a banker needs to calculate interest and yield for
investments, and so on. It reminds me of Homer Simpson, who once said, “English? Who needs
that? I’m never going to England!” However, you have decided to be a developer, and you will come
back to this time and time again, as many of the things that you need to do are based on simple
math principles. These can be applied with any framework or language.
Introduction to Math in Lua
There is a system library included with Lua that offers a series of math functions. The following is a
list of the functions available. Most of these functions are self-explanatory.
math.abs (x)
This returns the absolute value of x. If you pass this function a negative value, it returns the positive
value of x.
print(math.abs(−10)) -- Will return 10
math.acos (x)
This returns the arc cosine of the value x in radians.
print (math.acos(1)) -- Prints zero '0'
CHAPTER 4: Math with Lua
42
math.asin (x)
This returns the arc sine of the value x in radians.
print(math.asin(1)) -- Prints 1.5707963267949
math.atan (x)
This returns the arctangent of the value x in radians. This is in the range of –pi/2 to pi/2.
print(math.atan(1)) -- Prints 0.78539816339745
math.atan2 (y,x)
This returns the principal value of the arctangent of the quotient of the two numbers passed.
print(math.atan2(1, 0)) -- pi/2
print(math.atan2(−1, 0)) -- -pi/2
print(math.atan2(0, 1)) -- 0
print(math.atan2(0, -1)) -- pi
Note The parameters passed are y and then x, not x,y, as are generally passed.
math.ceil (x)
This returns the integer value of the passed value of x closest to the next integer.
print (math.ceil(0.1)) -- Returns 1
print (math.ceil(0.5)) -- Returns 1
print (math.ceil(0.6)) -- Returns 1
math.cos (x)
This returns the cosine value of x passed in radians.
print(math.cos(1)) -- 0.54030230586814
math.cosh (x)
This returns the hyperbolic cosine of a value.
print(math.cosh(1)) -- 1.5430806348152
CHAPTER 4: Math with Lua 43
math.deg (x)
This function converts a value from degree to radians.
print(math.deg(math.pi)) -- 180
math.exp (x)
This returns e, the base of natural logarithms raised to a given power.
print (math.exp(2)) -- 7.3890560989307
math.floor (x)
This returns the lower integer value from the passed value of x.
print (math.floor(0.1)) -- 0
print (math.floor(0.5)) -- 0
print (math.floor(0.9)) -- 0
math.fmod (x)
This returns the remainder of the division of the arguments that rounds the quotient toward zero,
according to the following equation:
remainder=numerator – quotient * denominator
The function itself is used like this:
print(math.fmod(7.5,3)) -- 1.5
math.frexp (x)
This function splits the value into a normalized fraction and an exponent. The results are two
numbers. The number x can be represented as follows:
fraction * 2^exponent
Here are some examples of the function in code:
print(math.frexp(2)) -- 0.5 2
print(math.frexp(3)) -- 0.75 1
print(math.frexp(1)) -- 0.5 1
math.huge
This is a constant than a function; it returns inf, which is a very large number.
print(math.inf)
CHAPTER 4: Math with Lua
44
math.ldexp (m, e)
This returns a number generated from the combination of the mantissa m and the exponent e. The
formula used is
number=m * 2^e
Here’s the function in use:
print(math.ldexp(0.5, 8)) -- 128
math.log (x)
This returns the natural logarithm value of x.
print(math.log(0.5)) -- (−0.69314718055995)
math.log10 (x)
This returns the base 10 logarithm value of x.
print (math.log10(0.5)) -- (−0.30102999566398)
math.max (x, …)
This returns the maximum value among the passed values.
print(math.max(2,5,3,8,3,4,5)) -- 8
math.min (x, …)
This returns the minimum value among the passed values.
print(math.min(2,5,3,8,3,4,5)) -- 2
math.modf (x)
This returns the integer and the fractional part of the number passed. So, if we passed it x.y, it would
return x and y.
print(math.modf(3.75)) -- 3 0.75
math.pi
This returns the math constant of pi.
print(math.pi) -- 3.1415926535898
CHAPTER 4: Math with Lua 45
math.pow (x,y)
This returns the number that is the result of raising the number x to y (i.e., xy
).
print(math.pow(3,3)) -- 27 = 3^3
print(math.pow(5,2)) -- 25 = 5^5
math.rad (x)
This returns the angle x converted into radians.
print(math.rad(math.pi)) -- 3.1415296535898
math.random ( [m [,n]] )
This returns a random value in the range between m and n. If the values of m and n are not passed,
then the function returns a value between 0 and 1. If a single value is passed to this function, then an
integer value between 1 and this number is returned.
print(math.random()) -- A decimal value between 0 and 1
print(math.random(10)) -- An integer value between 1 and 10
print(math.random(5,25)) -- An integer value between 5 and 25
math.randomseed (x)
This sets the seed for the random number generator. If you seed the value, you can get the same
random values.
math.sin (x)
This returns the sine of an angle passed in radians.
print(math.sin(30)) -- (−0.98803162409286)
math.sinh (x)
This returns the hyperbolic sine of a value.
print(math.sinh(1)) -- 1.1752011936438
math.sqrt (x)
This returns the square root of the number specified by x.
print(math.sqrt(144)) -- 12
print(math.sqrt(9)) -- 3
CHAPTER 4: Math with Lua
46
math.tan (x)
This returns the tangent of the angle passed in radians.
print (math.tan(45)) -- 1.6197751905439
math.tanh (x)
This returns the hyperbolic tangent of a value.
print(math.tanh(1)) -- 0.76159415595576
Practical Uses of Math in Gaming
If you develop games, you will be surrounded with math. The simplest scenario that any game will
involve is moving a character, and that involves moving the character on the x- or y-axis, or in plain
terms, moving it left and right or up and down. This movement of the character left and right is said
to be on the x-axis, and the up-and-down movement is on the y-axis.
Another example where you would use math is simple scorekeeping, in which you increment the
score by a value based on what object you might collect in the game. You would also use math to
handle players with multiple lives, whereby a value is decreased every turn until it reaches zero, after
which the game is over.
But first, let’s brush up on a few basics about math (even though we all learned it in school).
Assignment
The first thing that we shall look at is assignment. Remember the school days when we had
let x equal 5
let y equal 3
x+y=5+3
= 8
This concept remains even today. With Lua, when we assign a variable a value, this value can be one
of the eight basic types discussed in the Chapter 1. The most commonly used ones are numbers,
strings, and tables.
The preceding algebraic equation would translate to the following:
x=5
y=3
print( x+y= .. x+y)
Increasing and Decreasing
If you are coming to Lua from a C/C++ background, you may be used to operator overloading. This
is why a lot of developers ask why Lua doesn’t have the var++ or var-- operator to increment or
Random documents with unrelated
content Scribd suggests to you:
SUBJECT: Condition of Health of Mr. Gustav Krupp
von Bohlen
1. Mr. Gustav Krupp von Bohlen was examined by me today, and
the following findings are noticed.
2. Subject has suffered from progressive arteriosclerosis and
senility since 1939. He suffered an attack of cerebral thrombosis in
1942, which resulted in a temporary facial paralysis. About a year
ago he lost bladder and sphincter control.
3. At the present time he is bedridden, has to be fed and to be
cared for by nurses. He has no insight into his condition or situation
whatsoever and is unable to follow or keep up any conversation.
4. I do not believe that subject can be moved without serious
detriment to his health or that interrogation would be of any value
due to his loss of speech and complete lack of any understanding.
His course will be progressively down-hill.
5. In my judgment subject is not mentally competent to stand
trial in a court of justice.
/s/ WALTER PICK
Capt., MC, 232d Infantry
(Attachment II)
Blühbach, 13 September 1945
Otto Gerke, M.D.
Professor
Bad Gastein
Medical Certificate
Dr. Gustav Krupp von Bohlen und Halbach, born 7 August 1870,
has been treated by me for many years; he was examined by me
today. Since 1930 there has existed an arthrosis of the spine, as well
as a hypotony which as far back as 1932 caused fainting fits. Since
1937 a rapidly increasing sclerosis of the vessels was to be noted
which occurred in particular in the vessels of the brain.
In 1939 a fleeting paralysis of the eye muscles made its
appearance and passing disturbances of speech occured. In the
spring of 1942, the patient suffered an apoplectic stroke on the left
side, with facialisparosis and a distinct increase of reflexes on the
entire right side. The cerebral disturbances of circulation have
gradually grown worse despite treatments with medicaments. They
manifested themselves first in the form of impaired memory and will
power, indecision and general deterioration of intellectual faculties
and increased to the point of definite depressions accompanied by
apoplectic numbness and involuntary crying. There developed an
acute arteriosclerotic dementia.
In an automobile accident in December, 1944, the patient
suffered a fracture of the nose bone and the skull basis and had to
be treated for eight days in the Schwarzach Hospital at St. Veith.
Since that time, his physical condition has also deteriorated, and
several apoplectic fits have occurred as a consequence of multiple
softenings of the brain with heart symptoms and striary syndroms.
The patient is by now completely apathetic and disorientated.
There exists a motoric aphasy. Owing to rigor of the muscles, he can
neither walk nor stand up. For approximately the last six months he
has not been able to hold urine and stool. He is completely helpless
even in the simplest matters. There can be traced an advanced
emphysen in the lungs and a distinct myocardic impairment on the
basis of a coronary sclerosis of the heart. An enlargement of the
prostate gland has existed for years.
The prognosis of the condition is definitely unfavorable, an
improvement is not to be expected. Herr Von Bohlen is in no way
competent or capable of being interrogated.
/s/ DR. GERKE
(Attachment III)
HEADQUARTERS
42d DIVISION ARTILLERY
APO 411 US ARMY
20 October 1945
SUBJECT : Physical Examination of GUSTAV KRUPP VON BOHLEN
UND HALBACH
TO : General Secretary, International Military Tribunal, APO
403
1. The following history and physical examination of Herr Gustav
Krupp von Bohlen und Halbach is submitted in compliance with a
request from Mr. James Rowe. The history was obtained from Frau
Von Bohlen and from the valet. The information was obtained on the
19th and 20th of October 1945 when the patient was examined at
his home at Blühbach, Austria.
2. HISTORY OF PRESENT ILLNESS: Herr Von Bohlen has been
developing arteriosclerosis since 1932 according to his physician’s
reports. It is believed that he first had a very light apoplectic stroke
in 1937. This was very transitory in nature and cleared without
noticeable aftereffects except for some loss of the acuteness of his
thought processes and memory which his family noticed. In the
latter part of November 1944 he had a spell of unconsciousness, fell
and fractured a finger and was unable to walk alone for about 24
hours. On 15 December 1944, he was in an automobile accident and
received a severe blow and laceration of the forehead. He was
hospitalized as a result of this accident until the first week of
February 1945, at which time he returned home. Following this he
was able to walk only with assistance and he was unable to make
coherent statements. He continued to have light strokes and since
March has been unable to walk even with help, and his ability to
speak has gradually decreased until at the present time he is able
only to speak an occasional single word. Also since leaving the
hospital he has had no control of the bowels or bladder and during
the past three months has given no evidence of recognizing various
members of his family or close acquaintances.
3. PHYSICAL EXAMINATION:
GENERAL: The patient is an emaciated white male of 76 years of
age who is unable to speak or to cooperate in his own examination,
and appears to have no realization of what is going on about him.
SKIN: Scar 2 inches long extending across the forehead and
downward between the eyes and across the bridge of the nose.
The skin of the groin is macerated bilaterally as a result of being
constantly moistened with urine.
EYES, EARS, NOSE AND THROAT: No marked abnormalities.
LUNGS: Hyper-resonant throughout with moderate enlargement
of the chest cage suggesting the presence of mild emphysema.
CARDIOVASCULAR SYSTEM: Apex of heart palpable at a point 1
cm medial to the left mid-clavicular line. No evidence of right heart
enlargement could be detected. Pulse 80. Blood pressure 130/75.
Pulse full and regular except for an occasional skipped beat. The
distal palpable arteries in the wrist and ankles were markedly
sclerotic.
MUSCULO-SKELETAL SYSTEM: Both legs and arms were slowly
moved by the patient although all movements of the extremities
were associated with moderate spasticity. The patient was unable to
stand alone or walk when he was held upright.
NEUROLOGICAL SYSTEM: Pupillary reaction to light normal. Deep
tendon reflexes in arms and legs were normal. Normal reaction to
plantar stimulation.
GENITO-URINARY SYSTEM: Incontinence of urine was noted at
the time of examination. Genitalia appeared normal. A prostatic
examination was not made.
GASTRO-INTESTINAL SYSTEM: Abdominal examination was
normal. Incontinence of the bowels was noted at the time of the
examination.
4. IMPRESSION AND PROGNOSIS:
It is the impression of the undersigned that this man is suffering
from far advanced generalized arteriosclerosis which is progressive
and that he has already suffered from repeated small apoplectic
strokes. It is believed that this condition has already developed to
the point where this man has lost all capacity for memory, reasoning
or understanding of statements made to him and that transporting
or doing anything which might excite him might endanger his life.
/s/ PAUL F. CHESNUT
Capt., MC
Surgeon.
ACKNOWLEDGMENT OF SERVICE
The following declarations were received in writing from Hans
Fritzsche and from Erich Raeder on 18 October 1945:
I, Hans Fritzsche, have received today, on 18 October 1945, at
1950 Berlin time, the Indictment of the Chief of Counsel of the
International Military Tribunal, a statement regarding my right to
defense, a list of German lawyers, the Rules of the International
Military Tribunal in the German language. Above documents have
been handed to me by the Red Army Officer Grishajeff, acting on
orders of the International Military Tribunal and who advised me in
the German language on the contents of the documents and on my
right to defense.
Berlin, 18 October 1945.
/s/ HANS FRITZSCHE
I, Erich Raeder, have received today, on 18 October 1945, at
1850 Berlin time, the Indictment of the Chief of Counsel of the
International Military Tribunal, a statement regarding my right to
defense, a list of German lawyers, the Rules of the International
Military Tribunal in the German language. Above documents have
been handed to me by the Red Army Officer Grishajeff, acting on
orders of the International Military Tribunal and who advised me in
the German language on the contents of the documents and on my
right to defense.
Berlin, 18 October 1945.
/s/ ERICH RAEDER
MOTION ON BEHALF OF DEFENDANT
GUSTAV KRUPP VON BOHLEN
FOR POSTPONEMENT OF THE TRIAL AS TO HIM
Nuremberg, 4 November 1945
Theodor Klefisch
Lawyer
Cologne, 43, Blumenthalstrasse
To : The International Military Tribunal,
Nuremberg.
As defending counsel to the accused Dr. Gustav Krupp von
Bohlen und Halbach I request that the proceedings against this
accused be deferred until he is again fit for trial.
At any rate I request that the accused be not tried in his
absence.
Reasons
By Article 12 of the Charter of the International Military Tribunal
this Court has the right to try an accused in his absence if he cannot
be found, or if the Court deem this necessary for other reasons in
the interest of justice.
The 75-year-old accused Krupp von Bohlen has for a long time
been incapable of trial or examination owing to his severe physical
and mental infirmities. He is not in a position to be in contact with
the outside world nor to make or receive statements. The Indictment
was served on him on 19 October 1945 by a representative of the
International Military Tribunal by placing the document on his bed.
The accused had no knowledge of this event. Consequently he is not
aware of the existence of an Indictment. Naturally therefore he is
not capable of communicating either with his defense counsel nor
with other persons on the subject of his defense.
To prove the above two medical certificates are enclosed—that of
the court medical expert Doctor Karl Gersdorf of Werfen, Salzburg of
9 September 1945, and that of the Professor Doctor Otto Gerke of
Badgastein of 13 September.
Lately Herr Krupp von Bohlen has been examined several times
by American military doctors. As far as it is possible I should like to
request another complete medical examination. If the accused is
unable to appear before the Court, then according to Article 12 of
the Charter he could be tried only if the Court deemed it necessary
in the interests of justice.
Whatever may be understood by the phrase “in the interests of
justice” it would hardly be objective justice to try a defendant
accused of such serious crimes, if he were not informed of the
contents of the accusations or if he were not given the chance to
conduct his own defense or instruct a defense counsel. Particularly is
he in no condition to comprehend the following rights of an accused
set out in the Charter:
1. By Article 16, Section (a) of the Charter a copy of the
Indictment in a language which he understands will be served on the
accused at a suitably appointed time. The assurance given hereby
for a sufficient preparation of the proceedings can not be guaranteed
to Defendant Krupp von Bohlen on account of his state of disease.
According to Section (c) of the same Article 16 a preliminary
interrogation of the defendant shall take place in a language
intelligible to him. That is likewise impossible here. According to
Section (d) of Article 16 the defendant moreover can not exercise his
right of decision as to whether he will conduct his own defense or
whether he would like to be defended by counsel. Also the right of
the defendant as provided in Section (c) of producing evidence and
of cross examining witnesses himself or by his counsel in his behalf
can not be exercised by the defendant in view of his condition.
2. In the same manner as the Defendant Gustav Krupp von
Bohlen und Halbach is not able to exercise the confirmed rights
stated above in the preliminary proceedings he will also not be able
to exercise in the Trial those rights guaranteed to him by Article 24
of the Charter. In the first place this concerns the statement which
the accused has to render on inquiry as to whether he admits his
guilt or not, a statement which is of particular importance for the
course of the Trial and for the decision of the Tribunal. This is all the
more important as this statement regarding guilt or innocence can
be made exclusively by the accused himself according to his own
judgment and after examining his conscience. So far as the
procedure is admissible at all, the defense counsel could not at the
request of the Court express himself on the question of guilt, as
such a declaration presupposes the possibility of communication and
understanding with the accused.
Also the defendant could not exercise the right to the last word
to which he is entitled according to Article 24, Section (j).
The legislators who set up these guarantees for the defense
cannot wish to deny them undeservedly to an accused who can not
make use of them owing to illness. If by Article 12 of the Charter the
Trial of an absent defendant is allowed, then this exception to the
rule can be applied only to a defendant who is unwilling to appear
though able to do so. As is the case with the criminal procedure
rules of nearly all countries, it is on this principle that the rules and
regulations concerning the trial of absent defendants are based.
/s/ KLEFISCH
Lawyer
Medical Certificates Attached to Motion
on Behalf of Defendant
Gustav Krupp von Bohlen
(Attachment I)
Doctor’s Certificate
Dr. Gustav Krupp von Bohlen und Halbach, born 7 August 1870,
presently residing at Posthaus Blühbach, Werfen, Salzburg, suffers
from progressive arteriosclerotic softening of the brain (Paralysis
celebri) and as a consequence of this illness he requires constant
care and treatment. He is incapable of standing trial or of being
subjected to interrogation. An improvement of his condition is not to
be expected. Owing to his bad general physical condition
(Myodegeneratio cordis and Ataxis) he is not capable of traveling
either.
/s/ KARL GERSDORF, M. D.
District Doctor
Werfen, Salzburg
Certified Court Expert
Werfen, 8 September 1945
(Attachment II)
Attachment II is a medical certificate by Dr. Otto Gerke, printed
on page 120 ante.
REPORT OF MEDICAL COMMISSION
APPOINTED TO EXAMINE DEFENDANT
GUSTAV KRUPP VON BOHLEN[15]
7 November 1945
We, the undersigned, during the morning of 6 November 1945,
examined the patient, identified as Gustav Krupp von Bohlen by the
military authorities in charge, in the presence of his wife and nurse.
We unanimously agree that the patient was suffering from:
Senile softening of the brain, selectively affecting the frontal lobes of
the cerebral cortex and the corpus striatum, due to vascular
degeneration.
It is our unanimous, considered, professional opinion that the
mental condition of the patient, Gustav Krupp von Bohlen, is such
that he is incapable of understanding court procedure, and of
understanding or cooperating in interrogation.
The physical state of the patient is such that he cannot be moved
without endangering his life.
We are of the considered opinion that his condition is unlikely to
improve, but rather to deteriorate even further.
Therefore, we unanimously believe that he will never be fit,
mentally or physically, to appear before the International Military
Tribunal.
/s/ R. E. TUNBRIDGE
Brigadier, O.B.E., M.D., M.Sc., F.R.C.P.
Consulting Physician, British Army of the Rhine
/s/ RENE PIEDELIEVRE
M.D., Professor of the Paris Faculty of Medicine;
Expert of the Tribunal
/s/ NICOLAS KURSHAKOV
Professor of Medicine, Medical Institute of Moscow
Chief Internist, Commissariat of Public Health, U.S.S.R.
/s/ EUGENE SEPP
Emeritus Professor of Neurology, Medical Institute of Moscow
Member, Academy of Medical Sciences, U.S.S.R.
/s/ EUGENE KRASNUSHKIN
M. D., Professor of Psychiatry, Medical Institute of Moscow
/s/ BERTRAM SCHAFFNER
Major, Medical Corps
Neuropsychiatrist, Army of the United States
[15] At a meeting of the International Military Tribunal
on 30 October 1945, “it was agreed that a
committee of four medical officers, one appointed
by each Member of the Tribunal, be sent, if the
Committee of Prosecutors made no objection, to
examine Krupp and that they be empowered to
employ specialists if necessary.” The report of this
Medical Commission was presented 7 November
1945.
Report of the Medical Examination of
Herr Gustav Krupp von Bohlen
1. History: The following information was obtained by questioning
Frau Krupp von Bohlen, wife of the patient, Herr Krupp’s valet,
and Frl. Krone, private secretary of the patient.
The patient had been physically a very active man. He
hunted, rode and played tennis. With the aid of guides, he
was hunting deer as recently as 1943. He was abstemious
in his personal habits, did not smoke or partake of alcohol.
He retired to bed early, rarely remaining up after 2200
hours. He had eight children, six sons and two daughters.
There is no family history of mental disorder or of drug
addiction.
Previous Illness: There is no history of any major illness.
Since 1930, he has taken spa treatment each year for
arthritis of the spine and for hypotension. No radiographs
were available to indicate the true pathology of the spinal
condition. The valet stated that the patient, on the
recommendation of his physicians, had been very careful
with his diet during the past ten years.
Present Illness: For several years, the patient had been
subject to giddy attacks. In consequence, his wife was
always anxious when he went hunting, lest he should have
an attack whilst on the edge of a cliff, and fall and kill
himself. Two reliable guides always accompanied him on his
hunting excursions, and in 1942 Frau Krupp also joined in
expeditions in order to watch him.
Four years ago, the patient had a disturbance of vision
primarily due to dysfunction of the eye muscles. For a
period he had double vision. From this illness, he made an
apparent complete recovery.
Two years ago he had a stroke, with weakness of the
left side of the face, and impaired function of the right side
of the body. Following the latter incident, impairment of
gait, general weakness, and impairment of mental functions
became increasingly apparent. From the middle of 1944
onwards, the patient became more and more dependent
upon his wife; she was the only person who seemed to
understand fully his speech and his needs.
On November 25th, 1944, he was proceeding from the
garden towards the house, and suddenly seemed to run
(propulsion gait). Just before reaching the house, he fell
and injured his arm. As a result of this accident, he
attended the local hospital for treatment, traveling by
motor-car. On December 4th, whilst traveling to the hospital
at Schwarzach-St. Veith, and asleep in the back of the car,
the driver was compelled to swerve to avoid another
vehicle, and to brake suddenly. Herr Krupp von Bohlen was
thrown forward, and hit his forehead and the bridge of the
nose against a metal rail behind the driver’s seat. He did
not lose consciousness, but his condition was such that he
was detained in the hospital for approximately eight weeks.
During his stay in the hospital, he recognized his wife, his
relatives and the members of his staff, and spoke to them,
albeit haltingly.
Since the accident mentioned above, the general
condition of the patient has deteriorated rapidly. The
members of his staff had increasing difficulty in
understanding him. At first, with the aid of two people, he
was able to walk a few steps; until two months ago he sat
for short periods in a chair. The assistance of men-servants
was necessary for this task. He has been incontinent of
feces and urine since returning from the hospital in
February 1945. Since this date he has only spoken an
occasional single word, the words being simple ones and
without any rational association, apart from sporadic
expletives, such as “Ach, Gott” and “Donner Wetter”, when
disturbed. At times he has been exceedingly irritable and on
occasions has had inexplicable bouts of weeping. During
the past two months, he has become increasingly
apathetic, and no longer recognized relatives or friends.
Frau Von Bohlen thinks he may still recognize her as a
familiar face, but he exhibits no emotional reaction to her
presence. She thinks he realizes occasionally that strangers
are in the room; e. g., members of the Allied services, and
responds by being very tense.
Frl. Krone, secretary to the patient, stated that on
returning to Blühbach in September 1944, after an absence
since May 1944, she could no longer take down letters as
dictated by Krupp von Bohlen. Normally he was a very
punctilious man, and his diction and writing were correct
and very precise. She stated that after September 1944
there were frequent interruptions in his flow of ideas, his
syntax was faulty, and he occasionally did not appear to
appreciate the meaning of certain words. She would get an
idea of what he wanted to say, and then wrote the letter
herself in accordance with what she understood to be his
wishes. His handwriting also became increasingly illegible,
and he had difficulty in signing his name when giving power
of attorney to his relatives in January 1945.
The valet had been personal valet to Krupp for 20 years,
and traveled all over the world with him. He described his
master as a very active man, physically and mentally,
extremely punctilious in all personal details. He took a great
interest in his clothes, and was very observant of any slight
defect. In his personal habits he was abstemious, never
taking alcohol, and was also a non-smoker. Although a very
excellent sportsman and physically capable of considerable
feats of endurance when hunting, playing tennis or
climbing, he never overdid things and took care of himself
without in any way being overanxious about his health. The
valet first began to notice serious changes in the patient’s
personal habits two years ago, although in the valet’s
opinion, he had been failing slightly for about four to five
years. The degree of change, however, prior to two years
ago, was so slight and his master was in his opinion such a
“superman”, that the changes would not have been
apparent to the casual observer. Two years ago he began to
lose interest in the details of his personal clothing and to
become careless with his table manners. For instance,
when soup was served to him one day, he took his soup-
spoon and used it to take water from his wine-glass.
Latterly, he would sit at table and ask who was present,
although the only people in the room were intimate
members of his family. He would complain that the
telephone bell was ringing, and of people speaking to him;
these hallucinations became more frequent during the latter
part of 1944. The valet was employed as caretaker of the
main house by the American Military Government after the
cessation of hostilities in Europe, and did not see his
employer regularly after June 1945. On August 7, 1945, the
occasion of Gustav Krupp von Bohlen’s birthday, he called
to pay his respects, and for the first time he was not
recognized, and his master showed no appreciation of his
presence or his conversation.
2. General Appearance: The patient was lying rigidly in bed in a
Parkinsonian position with fine tremors of the jaw and hands.
The skin was atrophic and dry, and there was pigmentation of
the dorsum of the hands. The temporal arteries were prominent
and tortuous. The face was masklike, with dilated venules over
the cheeks. There was evidence of considerable wasting of the
body tissues, especially in the extremities, which also showed
evidence of trophic and acrocyanotic changes.
3. Neuropsychiatric Examination: The patient lay in bed with a
masklike face and in a fixed position on his back. The legs were
partially flexed, and similarly the elbows, the latter being pressed
firmly against the trunk. There was generalized muscular rigidity,
due to hypertenus of an extra-pyramidal tract lesion.
On the physicians’ entering the room, the patient fixed
his gaze on them, and replied to their greeting with “Guten
Tag,” and gave his hand when they offered theirs to him.
He shook hands normally, but he could not relax his hold or
remove his hand, and continued to squeeze the physician’s
hand; this was due to the presence of a forced grasp-reflex,
which was more marked in the left than in the right hand.
When asked how he felt, he replied “Gut,” but to all further
questions he gave no reply at all. He was silent and showed
no reaction to, or comprehension of, other questions, and
simple commands, such as “Open your mouth,” “Put out
your tongue,” “Look this way.” Only painful and
disagreeable stimuli produced any reaction, and then it was
merely a facial expression of discontent, sometimes
accompanied by grunts of disapproval.
The disturbance of verbal response was not due to
dysarthria, because the patient was able to pronounce such
words as he did use, quite distinctly. Neither was it due to
motor aphasia, because the few words he used were used
correctly, and he never exhibited the jargon responses of
the true aphasic when attempting to answer questions.
The patient was indifferent, apathetic, and was not in
good rapport with the external world, lacked initiative,
exhibited paucity of emotion. He uttered no spontaneous
speech, and his reaction to painful stimuli was primitive.
Neurological examination showed the following
additional abnormal findings: There was a right facial
weakness of a supranuclear origin. The pupils reacted
promptly to light, and appeared normal, save that the left
was slightly larger than the right. Ophthalmoscopic
examination of the fundi, limited by lack of cooperation
from the patient, showed clear media and normal retina
and retinal vessels. The right disc, the only one visualized,
appeared normal. Extra-ocular movements could not be
tested; there was no obvious strabismus. All deep reflexes
in the arms and legs were present and very brisk. Clonus
was not elicited. The plantar reflexes were flexor.
Abdominal reflexes were absent, except for the right upper.
There was incontinence of urine and feces, of the type
associated with senile dementia. There was an associated
minimal degree of intertrigo. Owing to lack of cooperation
of the patient a full sensory examination could not be
made, but the patient responded to pin-prick, deep
pressure and muscular movement throughout the body.
4. Cardio-vascular Examination:
Pulse: Rate 100, rhythm irregular. The irregularity was
due to extra-systoles. The radial arteries were just palpable,
without evidence of pathological thickening or tortuosity.
Blood pressure: systolic 130 mm. of mercury, diastolic 80
mm. of mercury.
Heart: The heart was clinically not enlarged. The cardiac
sounds were feeble, there was no accentuation of the
second sound in the aortic area, nor were any cardiac
murmurs audible. There were no vascular changes
observable in the vessels of the fundi. There was no
evidence of cedema or of congestive heart failure.
5. Respiratory Examination: Chest movement satisfactory. There was
no impairment of percussion noted. Auscultation revealed no
impairment of air entry, no alteration in the breath sounds, and
the absence of any adventitious sounds.
6. Alimentary-renal Examination: There was slight distention of the
abdomen, due to increase in the gaseous content of the
intestines. There was no evidence of ascites. The spleen was not
palpable, nor was there any evidence of glandular enlargement.
The liver was just palpable, one finger’s breadth below the right
costal margin, but there was no evidence of enlargement
upwards. Urinalysis: no sugar or albumen present.
7. Skeletal Examination: The patient’s rigidity limited the examination
of joints. There was limitation of movement of the neck due to
muscular hypertonus. The hypertonus was so marked in the
lower dorsal and lumbar region as to produce rigidity of the
spine. Attempts to move the joints passively stimulated
involuntary contractures of the muscles. There was evidence of
crepitus in both knee-joints.
DISCUSSION:
The clinical record presented by this patient is that of an
organic cerebral disorder, with predominant involvement of
the frontal lobes and basal ganglia. The mental
disintegration of the patient renders him incapable of
comprehending his environment, and of reacting normally
to it. He remains uniformly apathetic and disinterested,
intellectually retarded to a very marked degree, and shows
no evidence of spontaneous activity.
The above findings are such as are found in the
degenerative changes associated with senility. The findings
in the visceral organs are likewise compatible with the
diagnosis of senile degeneration.
The clinical course, from the evidence obtained, has
been that of a gradual decline over a period of years, with
more rapid deterioration during the past year. Such
deterioration will continue, and would be rapidly
accelerated, with immediate danger to the patient’s life,
were he to be moved from his present location.
DIAGNOSIS:
Senile degeneration of the brain tissues, selectively
affecting the frontal lobes of the cerebral cortex and the
basal ganglia, with associated senile degeneration of the
visceral organs.
/s/ R. E. TUNBRIDGE
Brigadier, O.B.E., M.D., M.Sc., F.R.C.P.,
Consulting Physician, British Army of the
Rhine
/s/ RENE PIEDELIEVRE
M.D., Professor of the Paris Faculty of
Medicine, Expert of the Tribunal
/s/ NICOLAS KURSHAKOV
M.D., Professor of Medicine, Medical
Institute of Moscow, Chief Internist,
Commissariat of Public Health U.S.S.R.
/s/ EUGENE SEPP
M.D., Emeritus Professor of Neurology,
Medical Inst, of Moscow; Member,
Academy of Medical Sciences, U.S.S.R.
/s/ EUGENE KRASNUSHKIN
M.D., Professor of Psychiatry, Medical
Institute of Moscow.
/s/ BERTRAM SCHAFFNER
Major, Medical Corps, Neuropsychiatrist,
Army of the United States
ANSWER OF THE UNITED STATES PROSECUTION
TO THE MOTION ON BEHALF OF DEFENDANT
GUSTAV KRUPP VON BOHLEN
INTERNATIONAL MILITARY TRIBUNAL
THE UNITED STATES OF AMERICA, THE FRENCH REPUBLIC, THE
UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND,
and THE UNION OF SOVIET SOCIALIST REPUBLICS
— against —
HERMANN WILHELM GÖRING, et al.,
Defendants.
ANSWER FOR THE UNITED STATES TO THE MOTION FILED IN
BEHALF OF KRUPP VON BOHLEN
The United States respectfully opposes the application on behalf
of Gustav Krupp von Bohlen und Halbach that his trial be “deferred
until he is again fit for trial.”
If the Tribunal should grant this application, the practical effect
would be to quash all proceedings, for all time, against Krupp von
Bohlen.
It appears that Krupp should not be arrested and brought to the
court room for trial. But the plea is that the Tribunal also excuse him
from being tried in absentia. This form of trial admittedly is
authorized by Article 12 of the Charter of the Tribunal. Of course,
trial in absentia in circumstance of the case is an unsatisfactory
proceeding either for prosecution or for defense. But the request
that Krupp von Bohlen be neither brought to court nor tried in his
absence is based on the contention that “the interests of justice”
require that he be thus excused from any form of trial. Public
interests, which transcend all private considerations, require that
Krupp von Bohlen shall not be dismissed unless some other
representative of the Krupp armament and munitions interests be
substituted. These public interests are as follows:
Four generations of the Krupp family have owned and operated
the great armament and munitions plants which have been the chief
source of Germany’s war supplies. For over 130 years this family has
been the focus, the symbol, and the beneficiary of the most sinister
forces engaged in menacing the peace of Europe. During the period
between the two World Wars, the management of these enterprises
was chiefly in Defendant Krupp von Bohlen. It was at all times
however a Krupp family enterprise. Only a nominal owner himself,
Von Bohlen’s wife, Bertha Krupp, owned the bulk of the stock. About
1937 their son, Alfried Krupp, became plant manager and was
actively associated in the policy making and executive management
thereafter. In 1940 Krupp von Bohlen, getting on in years, became
chairman of the board of the concern, thus making way for Alfried
who became president. In 1943 Alfried became sole owner of the
Krupp enterprises by agreement between the family and the Nazi
Government, for the purpose of perpetuating this business in Krupp
family control. It is evident that the future menace of this concern
lies in continuance of the tradition under Alfried, now reported to be
an internee of the British Army of the Rhine.
To drop Krupp von Bohlen from this case without substitution of
Alfried, drops from the case the entire Krupp family, and defeats any
effective judgment against the German armament makers. Whether
this would be “in the interests of justice” will appear from the
following recital of only the most significant items of evidence now in
possession of the United States as to the activities of Krupp von
Bohlen in which his son, Alfried, at all times aided as did other
associates in the vast armament enterprises, all plotting to bring
about the second World War, and to aid in its ruthless and illegal
conduct.
After the first World War, the Krupp family and their associates
failed to comply with Germany’s disarmament agreements but all
secretly and knowingly conspired to evade them.
In the 1 March 1940 issue of the Krupp Magazine, the Defendant
Krupp stated:
“I wanted and had to maintain Krupp in spite of all
opposition, as an armament plant for the later future, even
if in camouflaged form. I could only speak in the smallest,
most intimate circles, about the real reasons which made
me undertake the changeover of the plants for certain lines
of production . . . . Even the Allied snoop commissioners
were duped . . . . After the accession to power of Adolf
Hitler, I had the satisfaction of reporting to the Führer that
Krupp stood ready, after a short warming-up period, to
begin rearmament of the German people without any gaps
of experience . . . .”
Krupp von Bohlen (and Alfried Krupp as well) lent his name,
prestige and financial support to bring the Nazi Party, with an
avowed program of renewing the war, into power over the German
State. On 25 April 1931 Von Bohlen acted as chairman of the
Association of German Industry to bring it into line with Nazi policies.
On 30 May 1933 he wrote to Schacht that:
“It is proposed to initiate a collection in the most far-
reaching circles of German industry, including agriculture
and the banking world, which is to be put at the disposal of
the Führer of the NSDAP in the name of ‘The Hitler Fund’
. . . . I have accepted the chairmanship of the management
council.”
Krupp contributed from the treasury of the main Krupp company
4,738,446 marks to the Nazi Party fund. In June 1935 he contributed
100,000 marks to the Nazi Party out of his personal account.
The Nazi Party did not succeed in obtaining control of Germany
until it obtained support of the industrial interests, largely through
the influence of Krupp. Alfried first became a Nazi Party member and
later Von Bohlen did also. The Krupp influence was powerful in
promoting the Nazi plan to incite aggressive warfare in Europe.
Krupp von Bohlen strongly advocated and supported Germany’s
withdrawal from the Disarmament Conference and from the League
of Nations. He personally made repeated public speeches approving
and inciting Hitler’s program of aggression: On 6 and 7 April 1938
two speeches approved annexation of Austria; on 13 October 1938
approving Nazi occupation of the Sudetenland; on 4 September 1939
approving the invasion of Poland; on 6 May 1941 commemorating
success of Nazi arms in the West.
Alfried Krupp also made speeches to the same general effect.
Krupps were thus one of the most persistent and influential forces
that made this war.
Krupps also were the chief factor in getting ready for the war. In
January 1944, in a speech at the University of Berlin, Von Bohlen
boasted, “Through years of secret work, scientific and basic
groundwork was laid in order to be ready again to work for the
German Armed Forces at the appointed hour without loss of time or
experience.” In 1937, before Germany went to war, Krupps booked
orders to equip satellite governments on approval of the German
High Command. Krupp contributed 20,000 marks to the Defendant
Rosenberg for the purpose of spreading Nazi propaganda abroad. In
a memorandum of 12 October 1939 a Krupp official wrote offering to
mail propaganda pamphlets abroad at Krupp expense.
Once the war was on, Krupps, both Von Bohlen and Alfried being
directly responsible therefor, led German industry in violating treaties
and international law by employing enslaved laborers, impressed and
imported from nearly every country occupied by Germany, and by
compelling prisoners of war to make arms and munitions for use
against their own countries. There is ample evidence that in Krupp’s
custody and service they were underfed and overworked, misused,
and inhumanly treated. Captured records show that in September
1944 Krupp concerns were working 54,990 foreign workers and
18,902 prisoners of war.
Moreover, the Krupp companies profited greatly from destroying
the peace of the world through support of the Nazi program. The
rearmament of Germany gave Krupp huge orders and corresponding
profits. Before this Nazi menace to the peace began, the Krupps
were operating at a substantial loss. But the net profits after taxes,
gifts, and reserves steadily rose with rise of Nazi rearmament, being
as follows:
For year ending 30 September 1935— 57,216,392 marks
For year ending 30 September 1938— 97,071,632 marks
For year ending 30 September 1941— 111,555,216 marks
The book value of the Krupp concerns mounted from 75,962,000
marks on 1 October 1933, to 237,316,093 marks on 1 October 1943.
Even this included many going concerns in occupied countries at a
book value of only 1 mark each. These figures are subject to the
adjustments and controversies usual with financial statements of
each vast enterprise but approximately reflect the facts about
property and operations.
The services of Alfried Krupp and of Von Bohlen and their family
to the war aims of the Nazi Party were so outstanding that the Krupp
enterprises were made a special exception to the policy of
nationalization of industries. Hitler said that he would be “prepared
to arrange for any possible safeguarding for the continued existence
of the works as a family enterprise; it would be simplest to issue ‘lex
Krupp’ to start with”. After short negotiations, this was done. A
decree of 12 November 1943 preserves the Krupp works as a family
enterprise in Alfried Krupp’s control and recites that it is done in
recognition of the fact that “for 132 years the firm of Fried. Krupp,
as a family enterprise has achieved outstanding and unique merits
for the armed strength of the German people.”
It has at all times been the position of the United States that the
great industrialists of Germany were guilty of the crimes charged in
this Indictment quite as much as its politicians, diplomats, and
soldiers. Its chief of counsel, on 7 June 1945, in a report to
President Truman, released by him and with his approval, stated that
the accusations of crimes include individuals in authority in the
financial, industrial, and economic life of Germany as well as others.
Pursuant thereto, the United States, with approval of the
Secretary Of State, proposed to indict Alfried Krupp, son of Krupp
von Bohlen, and president and owner of the Krupp concern. The
Prosecutors representing the Soviet Union, the French Republic, and
the United Kingdom unanimously opposed inclusion of Alfried Krupp.
This is not said in criticism of them or their judgment. The necessity
of limiting the number of defendants was considered by
representatives of the other three nations to preclude the addition of
Alfried Krupp. Immediately upon service of the Indictment, learning
the serious condition of Krupp von Bohlen, the United States again
called a meeting of Prosecutors and proposed an amendment to
include Alfried Krupp. Again the proposal of the United States was
defeated by a vote of 3 to 1. If now the Tribunal shall exercise its
discretion to excuse from trial the one indicted member of the Krupp
family, one of the chief purposes of the United States will be
defeated and it is submitted that such a result is not “in the interests
of justice.”
The United States respectfully submits that no greater disservice
to the future peace of the world could be done than to excuse the
entire Krupp family and the armament enterprise from this Trial in
which aggressive war making is sought to be condemned. The
“interests of justice” cannot be determined without taking into
account justice to the men of four generations whose lives have
been taken or menaced by Krupp munitions and Krupp armament,
and those of the future who can feel no safety if such persons as
this escape all condemnation in proceedings such as this.
While of course the United States cannot, without the
concurrence of one other Power indict a new defendant, it can under
the Charter alone oppose this motion. The United States respectfully
urges that if the favor now sought by Krupp von Bohlen is to be
granted, it be upon the condition that Alfried Krupp be substituted or
added as a defendant so that there may be a representative of the
Krupp interests before the Tribunal.
It may be suggested that bringing in a new defendant would
result in delay. Admitting, however, that a delay which cannot
exceed a few days may be occasioned, it is respectfully suggested
that the precise day that this Trial will start is a less important
consideration than whether it is to fail of one of its principal
purposes. The American Prosecution staff has been by long odds the
longest and farthest away from home in this endeavor. On personal
as well as public interest consideration it deplores delay. But we
think the future as well as the contemporary world cannot fail to be
shocked if, in a trial in which it is sought to condemn aggressive war
making, the Krupp industrial empire is completely saved from
condemnation.
The complete trial brief of the United States on Krupp von Bohlen
with copies of the documents on which his culpability is asserted will
be made available to the Tribunal if it is desired as evidence
concerning him and Alfried Krupp and the Krupp concerns.
Respectfully submitted:
/s/ ROBERT H. JACKSON
Chief of Counsel for the United States of
America
12 November 1945
MEMORANDUM OF THE BRITISH PROSECUTION
ON THE MOTION ON BEHALF OF DEFENDANT
GUSTAV KRUPP VON BOHLEN
British War Crimes Executive (E.S.)
12 November 1945
To: The International Military Tribunal.
The British Chief Prosecutor has had the opportunity of
considering the application of the Defending Counsel to the accused
GUSTAV KRUPP VON BOHLEN UND HALBACH:
1) that the proceedings against this accused be deferred until he
is again fit for trial;
2) at any rate, that the accused be not tried in his absence.
The British Chief Prosecutor opposes this application for the
following reasons:
i) The medical position is that as far as can be foreseen the said
defendant will never again be fit for trial, and therefore if he is
not tried in his absence, he will not be tried at all.
ii) Although in an ordinary case it is undesirable that a defendant
should be tried when he is unable to comprehend the charges
made against him, or to give instruction for his defence, there
are special considerations which apply to this case and make it
essential for the Defendant Gustav Krupp von Bohlen und
Halbach to be tried in his absence.
iii) As this is a case of conspiracy, the British Prosecutor submits
that all the evidence directly concerned with the actions and
speeches of the said defendant and the operations of Fried.
Krupp A.G. would be evidence against the remaining
defendants, if the Prosecution establishes a prima facie case:
a) that the conspiracy existed;
b) that the said defendant was a party to the conspiracy.
Such prima facie case is clearly indicated in the Indictment
lodged with the Tribunal and the evidence against the present
defendant set out in the American Answer to this Application.
iv) If this submission of the British Chief Prosecutor is correct and
this evidence can and will be given in Court, then it is at least
arguable that it is preferable for the said defendant to be
represented so that his lawyer can deal with such evidence to
the best of his ability.
v) It is a matter of common knowledge of which the Court may
take cognisance that the business of Fried. Krupp A.G. is a vast
organisation. There are, therefore, many sources within the
Krupp firm from which the defending Advocate can obtain
information which will enable him to deal with the allegations
contained in the American Answer. If the Defendant Gustav
Krupp is not retained in the list of defendants, there will be no
advocate so well qualified to deal with those allegations on
behalf of the other defendants, against whom they will still be
preferred.
vi) In the circumstances of this trial the kernel of the case for the
prosecution is that a number of conspirators have agreed and
worked together for the purpose of waging aggressive war and
causing untold misery to the World. The public interest, that
the defendant who is responsible for the preparation of
armaments on the one hand, and the utilisation on arms
production, of prisoners of war and forced labour, including
detainees from Concentration Camps on the other, is one of
“the interests of justice” within Article 12 of the Charter.
vii) Finally, it is earnestly desired that the wishes of the Tribunal as
publicly announced at Berlin on the 18th October that the trial
should open on the appointed day, namely, 20th November be
realised and carried into execution. The British Delegation is
strongly opposed to any postponement.
/s/ HARTLEY SHAWCROSS
British Chief Prosecutor
MEMORANDUM OF THE FRENCH PROSECUTION
ON THE MOTION ON BEHALF OF DEFENDANT
GUSTAV KRUPP VON BOHLEN
Nuremberg, 13 November 1945
MEMORANDUM
by the French Delegation concerning the matter of Krupp
which was discussed at the meeting of 12 November 1945
France is formally opposed to dropping the firm of Krupp from
the Trial since the other prosecutors do not contemplate the
possibility of preparing at this time a second trial directed against
the big German industrialists.
France objects therefore to a simple severance.
The remaining possibilities are either the trial of Krupp Sr. in
absentia or the substitution of Krupp Jr. in his father’s place and
stead.
The trial of an old man who is about to die and who is not before
the Court is difficult in itself.
France would prefer to substitute his son against whom there are
serious charges.
For simple reasons of expediency, France requests that there be
no delay in excess of the delay that will result in all probability from
the motions of the Defense.
If the Tribunal denies these motions of the Defense, the Trial of
Krupp Sr. should take place in his absence.
However, this is in our opinion the lesser of two evils.
/s/ DUBOST
SUPPLEMENTAL MEMORANDUM OF THE FRENCH
PROSECUTION
Nuremberg, 14 November 1945
ADDITIONAL MEMORANDUM
We consider the trial of KRUPP, the father, as impossible under
the circumstances. The trial of an old, dying man, absent from the
dock, cannot take place.
We wish that the son be prosecuted. There are serious charges
against him.
We had requested, so far, that he be prosecuted without any
delay arising in the Trial therefrom.
The reasons of opportunity which had induced us to adopt this
attitude are no longer so imperative since the Soviet Delegation has
concurred in Mr. Jackson’s thesis.
Consequently we no longer raise any objection and we concur
ourselves in this thesis.
The Deputy-Delegate of
The French Government
in the Prosecution of
The International Military Tribunal
/s/ CH. DUBOST
ORDER OF THE TRIBUNAL GRANTING
POSTPONEMENT OF PROCEEDINGS AGAINST
GUSTAV KRUPP VON BOHLEN
INTERNATIONAL MILITARY TRIBUNAL
THE UNITED STATES OF AMERICA, THE FRENCH REPUBLIC, THE
UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND,
and THE UNION OF SOVIET SOCIALIST REPUBLICS
— against —
HERMANN WILHELM GÖRING, et al.,
Defendants.
ORDER
ON CONSIDERATION of the application of counsel for the
defendant, Gustav Krupp von Bohlen, for a postponement of the
proceedings against him;
IT IS ORDERED that the application for postponement be, and
the same hereby is, granted;
IT IS FURTHER ORDERED that the charges in the indictment
against Gustav Krupp von Bohlen shall be retained upon the docket
of the Tribunal for trial hereafter, if the physical and mental condition
of the defendant should permit.
BY THE INTERNATIONAL MILITARY TRIBUNAL
/s/ GEOFFREY LAWRENCE
President.
Dated this 15th day
of November, 1945.
ATTEST:
/s/ WILLIAM L. MITCHELL
General Secretary.
SUPPLEMENTARY STATEMENT OF
THE UNITED STATES PROSECUTION
MEMORANDUM FILED BY THE UNITED STATES CHIEF OF COUNSEL
TO THE INTERNATIONAL MILITARY TRIBUNAL
The United States, by its Chief of Counsel, respectfully shows:
The order of the Tribunal, that “The charges in the Indictment
against Gustav Krupp von Bohlen shall be retained upon the docket
of the Tribunal for trial hereafter, if the physical and mental condition
of the defendant should permit,” requires the United States to make
clear its attitude toward subsequent trials, which may have been
misapprehended by the Tribunal, in order that no inference be drawn
from its silence.
The United States never has committed itself to participate in any
Four Power trial except the one now pending. The purpose of
accusing organizations and groups as criminal was to reach, through
subsequent and more expeditious trials before Military Government
or military courts, a large number of persons. According to estimates
of the United States Army, a finding that the organizations presently
accused are criminal organizations would result in the trial of
approximately 130,000 persons now held in the custody of the
United States Army; and I am uninformed as to those held by
others. It has been the great purpose of the United States from the
beginning to bring into this one trial all that is necessary by way of
defendants and evidence to reach the large number of persons
responsible for the crimes charged without going over the entire
evidence again. We, therefore, desire that it be a matter of record
that the United States has not been, and is not by this order,
committed to participate in any subsequent Four Power trial. It
reserves freedom to determine that question after the capacity to
handle one trial under difficult conditions has been tested.
Respectfully submitted:
/s/ ROBERT H. JACKSON
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PPTX
Programming languages
PDF
Key Features Of The Pseudo Code
PDF
Which programming language should you learn next?
PDF
Selje_Fox on the Run.pdf
PDF
Procedural Programming Of Programming Languages
PDF
Computer Science Is The Study Of Principals And How The...
PDF
Which Programming Languages To Choose For Android App Development_.pdf
PPTX
What is the best programming language to learn if you want to work on the blo...
Programming languages
Key Features Of The Pseudo Code
Which programming language should you learn next?
Selje_Fox on the Run.pdf
Procedural Programming Of Programming Languages
Computer Science Is The Study Of Principals And How The...
Which Programming Languages To Choose For Android App Development_.pdf
What is the best programming language to learn if you want to work on the blo...

Similar to Learn Lua For Ios Game Development 1st Ed Jayant Varma (20)

PDF
Learning Airtable (First Early Release) Elliott Adams
PDF
Enterprise ipad Development with notes
PDF
Top Reasons to Choose Flutter App Development Company.pdf
PPTX
15 Top reasons to choose Java for Backend Development
PPTX
Uses of java
PDF
The Guide to becoming a full stack developer in 2018
PPT
Different programming languages
PDF
Languages used by web app development services remotestac x
PPTX
PPTX
IT Technologies Career perspective
PDF
Intro to web development
PDF
Java application-development
PDF
Java As A Programming Language
PPTX
Computer languages
PPTX
9 reasons why programmers should learn react native
PDF
iOS Application Development Step by Step to develop an iOS App.pdf
PPTX
Time to learn flutter or stick to native development
PDF
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
PDF
Best Programming Languages to Learn This Year
PDF
Apple Cell Phones
Learning Airtable (First Early Release) Elliott Adams
Enterprise ipad Development with notes
Top Reasons to Choose Flutter App Development Company.pdf
15 Top reasons to choose Java for Backend Development
Uses of java
The Guide to becoming a full stack developer in 2018
Different programming languages
Languages used by web app development services remotestac x
IT Technologies Career perspective
Intro to web development
Java application-development
Java As A Programming Language
Computer languages
9 reasons why programmers should learn react native
iOS Application Development Step by Step to develop an iOS App.pdf
Time to learn flutter or stick to native development
Ruby vs Java: Comparing Two Popular Programming Languages For Developing Ente...
Best Programming Languages to Learn This Year
Apple Cell Phones
Ad

Recently uploaded (20)

PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Computing-Curriculum for Schools in Ghana
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Cell Structure & Organelles in detailed.
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Practical Manual AGRO-233 Principles and Practices of Natural Farming
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Updated Idioms and Phrasal Verbs in English subject
PDF
RMMM.pdf make it easy to upload and study
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Supply Chain Operations Speaking Notes -ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
Computing-Curriculum for Schools in Ghana
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Yogi Goddess Pres Conference Studio Updates
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Cell Structure & Organelles in detailed.
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Practical Manual AGRO-233 Principles and Practices of Natural Farming
LDMMIA Reiki Yoga Finals Review Spring Summer
What if we spent less time fighting change, and more time building what’s rig...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Updated Idioms and Phrasal Verbs in English subject
RMMM.pdf make it easy to upload and study
Microbial diseases, their pathogenesis and prophylaxis
Supply Chain Operations Speaking Notes -ICLT Program
Ad

Learn Lua For Ios Game Development 1st Ed Jayant Varma

  • 1. Learn Lua For Ios Game Development 1st Ed Jayant Varma download https://ebookbell.com/product/learn-lua-for-ios-game- development-1st-ed-jayant-varma-55199758 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Learn Lua For Ios Game Development 1st Ed Varma Jayant https://ebookbell.com/product/learn-lua-for-ios-game-development-1st- ed-varma-jayant-6618286 Lua Programming Beginners Learn Lua Programming Step By Step Very Easy Rizk https://ebookbell.com/product/lua-programming-beginners-learn-lua- programming-step-by-step-very-easy-rizk-37070252 Lua Programming Beginners Learn Lua Programming Step By Step Very Easy Rizk https://ebookbell.com/product/lua-programming-beginners-learn-lua- programming-step-by-step-very-easy-rizk-232145960 Learn Javafx Game And App Development With Fxgl 17 1st Edition Almas Baimagambetov https://ebookbell.com/product/learn-javafx-game-and-app-development- with-fxgl-17-1st-edition-almas-baimagambetov-44879768
  • 3. Learn C The Hard Way Practical Exercises On The Computational Subjects You Keep Avoiding Like C Zed A Shaw https://ebookbell.com/product/learn-c-the-hard-way-practical- exercises-on-the-computational-subjects-you-keep-avoiding-like-c-zed- a-shaw-44988700 Learn To Read Ancent Sumerian An Introduction For Complete Begiknners Joshua Bowen https://ebookbell.com/product/learn-to-read-ancent-sumerian-an- introduction-for-complete-begiknners-joshua-bowen-45333320 Learn C Programming A Beginners Guide To Learning The Most Powerful And Generalpurpose Programming Language With Ease 2nd Edition 2nd Jeff Szuhay https://ebookbell.com/product/learn-c-programming-a-beginners-guide- to-learning-the-most-powerful-and-generalpurpose-programming-language- with-ease-2nd-edition-2nd-jeff-szuhay-45462930 Learn Enough Ruby To Be Dangerous Write Programs Publish Gems And Develop Sinatra Web Apps With Ruby Michael Hartl https://ebookbell.com/product/learn-enough-ruby-to-be-dangerous-write- programs-publish-gems-and-develop-sinatra-web-apps-with-ruby-michael- hartl-46132216 Learn Guitar The Easy Way The Easy Way To Play Guitar Using Simplified Chords Paolo Ocampo https://ebookbell.com/product/learn-guitar-the-easy-way-the-easy-way- to-play-guitar-using-simplified-chords-paolo-ocampo-46157382
  • 6. For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
  • 7. v Contents at a Glance About the Author�������������������������������������������������������������������������������������������������������������� xxv About the Technical Reviewers�������������������������������������������������������������������������������������� xxvii Acknowledgments����������������������������������������������������������������������������������������������������������� xxix Chapter 1: Introduction to Lua ■ ■ �������������������������������������������������������������������������������������������1 Chapter 2: Lua Libraries ■ ■ ��������������������������������������������������������������������������������������������������13 Chapter 3: File Operations ■ ■ �����������������������������������������������������������������������������������������������29 Chapter 4: Math with Lua ■ ■ ������������������������������������������������������������������������������������������������41 Chapter 5: Strings ■ ■ �����������������������������������������������������������������������������������������������������������65 Chapter 6: Threading ■ ■ �������������������������������������������������������������������������������������������������������77 Chapter 7: Tips and Tricks ■ ■ �����������������������������������������������������������������������������������������������97 Chapter 8: Corona SDK ■ ■ ��������������������������������������������������������������������������������������������������127 Chapter 9: Gideros Studio ■ ■ ����������������������������������������������������������������������������������������������167 Chapter 10: Moai ■ ■ �����������������������������������������������������������������������������������������������������������203 Chapter 11: LÖVE ■ ■ �����������������������������������������������������������������������������������������������������������245 Chapter 12: Codea ■ ■ ���������������������������������������������������������������������������������������������������������279
  • 8. vi Contents at a Glance Chapter 13: Libraries ■ ■ �����������������������������������������������������������������������������������������������������303 Chapter 14: Third-Party Applications ■ ■ ����������������������������������������������������������������������������317 Chapter 15: Sample Source Code ■ ■ ����������������������������������������������������������������������������������349 Index���������������������������������������������������������������������������������������������������������������������������������377
  • 9. 1 Chapter 1 Introduction to Lua Apple has been issuing checks to developers, and the 2012 figures indicate that it has so far been to the tune of $5 billion. In the past, it used to be desktops with Microsoft-based products that were raking in money for developers, with Visual Basic, or earlier with database products such as dBase and FoxPro. While the major share of this revenue goes to larger companies such as EA, Chillingo, Gameloft, Rovio and even Disney, a lot of indie developers and smaller companies vie for a share of that big pie. Who knows what idea might just become the money-spinner for a developer. Robert Nay, a 14-year-old, made the game Bubble Ball while he was learning to code, and it went viral, with over 8 million downloads. And no one knows what the next top game will be. As a person that has an interest in development, you have made the first step in this journey. You could be a student that has never developed before, or you could be a guru developer who can whip up an enterprise app in minutes. The point is that whatever your background, you are for some reason drawn to this strange-sounding language, Lua (pronounced LOO-ah.). What Is Lua? Lua is a programming language that has a small footprint, works across several platforms, and is quite flexible and extensible. Further, Lua is a game changer for developers that want to write apps for the mobile devices. It has powered a lot of apps and games in the Apple App Store, and it has been spoken about by the late Steve Jobs. It has even been linked with one of the most advanced self-replicating and mutating viruses, the Flame. Despite all of that, Lua remains to be a language that seems more like plain English than a cryptic programmer’s language, making it a language with a smaller learning curve. The History of Lua While knowing the history of Lua will not change anything in terms of making anyone a better programmer, it important to get an idea of why you’d want to use Lua. Lua was created at the Pontifical Catholic University of Rio de Janeiro, Brazil, by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes, who were members of the
  • 10. CHAPTER 1: Introduction to Lua 2 Computer Graphics Technology Group (TeCGraf). Generally, funding for university research is provided by industry, which also expects solutions to some problems that they face. Petrobas, a Brazilian oil company, one of the clients this group was helping them resolve issues related to data entry. Operations of a petroleum company are large, and a large number of data transactions were to be processed on a daily basis. They approached the group to devise a graphical front end that would help eliminate errors in data entry, especially when working with legacy code from fixed-format files. TeCGraf looked at the whole series of screens that were provided to them and tried to find some form of uniformity to help find a solution. For this they came up with a simple and unified data entry language (DEL), which was used to describe the data in each data entry task. I think a good parallel would be that of XML, but without the multitude of tags that make it confusing to understand. That way one could define the entities and the restrictions or rules. This became very popular, as it was easy to define entities and create records that would help validate the data. With popularity came feature requests, so the users that were using DEL now required more functionality, which was pushing DEL from being a descriptive language to a programming language with requests such as loops, conditional control, and so on. If you were a software developer in the ’90s, you will realize that one of the aspects that many developers spent time on was changing the color and font of the data entry screens. The group created another specialized description language that allowed for setting these attributes. This was called Simple Object Language (SOL), as it allowed the user to create an object and manipulate the color, font, and other characteristics of the object. (Sol also means sun in Portuguese.) The architecture of this language was made more like that of a compile-and-run-type of language than that of an IDE-type application. The API was implemented as a C library and linked to the main program. Each type could have a callback function that functioned as the constructor (i.e., the function is called when an object of a particular type is created). In 1993, the creators realized that DEL and SOL could both be combined into a single more powerful language. This led to a proper programming language that would have it all: assignment, control structures, subroutines, functions, and so on. However, it would also work with the basic requirement to be able to offer data-description facilities like those of DEL or SOL. They wanted it to be an easy–to-use language without cryptic syntax and semantics, as the end users weren’t expected to be professional programmers. Lastly, they wanted it to be portable to run on any and every platform (if required). Because it was a modified version of SOL, the creators called this new program Lua (which mean moon in Portuguese). Lua Timeline As of this writing, Lua is in version 5.2.1. It has undergone quite a few changes and has been used extensively in many projects for enterprise, entertainment, games, and apps. For many of us, it might come as a surprise that Lua is used in South American homes practically on a daily basis. It powers their interactive televisions. Universities use Lua in their research to allow for quick processing and results. In 1996, Lua got exposure internationally after an article in Dr. Dobbs. Following the article, there were e-mails from developers. In a paper, Roberto narrates about how Bret Mogilefsky, who was
  • 11. CHAPTER 1: Introduction to Lua 3 An application is made up of all the resources graphics, music, text, etc.), which are compiled into the application, with the Lua code along with the framework stub. When run, the framework or the engine creates an OpenGL surface on which all of the graphics are displayed. This is how all of the frameworks work, and this is how they can offer cross-platform compatibility. The limitations on the framework are imposed mainly due to either the limitations of OpenGL or the framework engine. the lead programmer at LucasArts (of Grim Fandango fame), wanted to replace their scripting language SCUMM with Lua. This drew interest from other developers, and Lua started to appear on newsgroups. Starting with Lua One important point that I’ll make throughout the book is that, with Lua, it doesn’t matter what framework you use; what’s important is the glue that holds it all together: Lua. In the ’90s, Microsoft was pushing client-server and three-tier architecture (similar to what Apple has been pushing as MVC [Model-View-Controller]). The idea behind MVC is that it involves three distinct portions: a model, which takes care of the data; a view, which displays the data from the model and provides interaction with the user; and a controller, which communicates between the model and the view, as these two do not have any idea of each other’s existence. The controller is the broker that helps the two talk to each other. The most usual way to work with MVC is to use a framework, which takes care of a lot of the details for you. In this book, I shall cover a few frameworks: CoronaSDK, Gideros Studio, Moai, Codea, and LÖVE. All of these except LÖVE help develop and run apps on the iOS platform. The architecture of a Lua-based mobile app is simple, as the diagram in Figure 1-1 shows. Figure 1-1. The architecture of an app using Lua on a mobile device platform
  • 12. CHAPTER 1: Introduction to Lua 4 The MVC pattern discussed earlier holds true in this architecture. If we write our code with this in mind, we can create not only cross-platform applications, but cross-framework ones. The controller code that we write in Lua will change to cater for the other framework, but the rest of the code will be the same. In the next section, we shall focus on Lua and how to use it. After that, we’ll look specifically at the frameworks and integrate some of the things that you’ve learned. Setting Up Lua If we need to work with Lua, we need to have Lua. Since most of the frameworks use Lua 5.1.4, we shall use that version for compatibility. Lua can be obtained as a precompiled binary or source code that you can compile. It is also available for a variety of platforms, including Windows, Mac, *nix, iOS, and Android. Online Lua Shell This is perhaps the easiest way to test out the Lua code, and involves no installation or setup of any kind. You can simply navigate to www.lua.org/demo.html. Windows, Mac OS X, and *nix You can download the binaries for Lua version 5.1.4 from http://sourceforge.net/projects/luabinaries/files/5.1.4/Executables/. You can choose lua5 1 4 Win32 bin.zip or lua 5 1 4 Win64 bin.zip as per your version of Windows. For the Mac, there are versions for Tiger, Leopard, Snow Leopard, and Lion. For *nix, they are based on the kernel version; in this case, it’s easier to download Lua from the app catalog in each of the distributions. iOS There are two apps that I know of that allow for running Lua code interactively. Unlike the other Lua offerings mentioned, these are not free.  iLuaBox: This app uses the newer version of Lua 5.2 and costs about $2.99 in the App Store.  Lua Console: This app works with Lua 5.1.4 and costs $1.99 in the App Store. Of the two, iLuaBox has some advanced functionality in terms of managing files and directories. Features of Lua Lua is implemented as a library written in C. It does not have a main program, as there is no need to invoke something automatically; it works as in embedded mode and calls the embedding program. This code can invoke other functions, assign variables, and read and write the data. Having been written in C, it can also be extended; however, the official release will only add features that have been approved by a committee.
  • 13. CHAPTER 1: Introduction to Lua 5 Variables In simple computing terminology, a variable is a location that holds a value and can be accessed by giving it a name. Think of it as a filing cabinet in a company’s HR department. It can hold many files with details on the employees. When you need to access data from one of them, you can look it up via the file’s name tag. If you have two employees with the same first and last names, there need to be two files and the name tag would require some form of identification to distinguish between the two. Just as you cannot have two files with the same tag, you cannot have two variables with the same name. There has to be some point of differentiation (e.g., tag1 and tag2 instead of just tag). The names given to the variables can be a series of letters, digits, and underscores; however, they cannot begin with a digit. The names are case sensitive, so there is a difference between T and t. In addition to variables, Lua also uses keywords, which cannot be used for variable names, as Lua identifies them as commands for the code, not variable names. Here’s the list of system keywords, which cannot be used as variable names): and break do else elseif end false for function if in local nil not or repeat return then true until while
  • 14. CHAPTER 1: Introduction to Lua 6 Hello World, the Variable Way To begin with, we need to start Lua in interactive mode for the purpose of running all of our code. The way it works is to open a terminal in Mac OS X or *nix, type lua, and press Enter. After doing this, you should see the screen shown in Figure 1-2. Under Windows, you can start the Lua console from the Start menu. Note In this book, most of the screenshots and references will be for the Mac OS X version. Figure 1-2. The Lua interactive shell running in the terminal on a Mac Theon the line is the prompt where you can type the Lua code you want to run. We shall start with writing a simple Hello World example. Type the following at the prompt: print (Hello World) You should see the text “Hello World” printed on the next line. The print function is used to display the text in the terminal. Let's take this a step further:
  • 15. CHAPTER 1: Introduction to Lua 7 message = Hello World print(message) What we have just done here is assign the string Hello World to the message variable; then we use the print function to display the value of message in the terminal. Just like strings, we can also print numbers, and the simplest way to do so is print(5) age = 1 print(age) print(Age :, age) print(1,2,3,4,5,One) The aim of this is to demonstrate that using print, we can display variables, numbers, and strings to the terminal. Strings Strings in Lua can be enclosed in single or double quotes. So, for example, both 'Lua' and Lua are valid. Literal strings can be used in a manner similar to C by preceding them with a blackslash () and enclosing them in the single or double quotes. These can be used to include commonly used escape sequences such as b, t, v, r, n, , ', and . They can also be used to specify a numeric value with the format ddd, where d is a digit. print(65) There are times when you want to include chunks of text, and keeping track of the quotation marks can sometimes get a bit tricky, especially when trying to get them to match and line up. In such cases, you can use the long-bracket format, by which you enclose the text within [[ and ]]. Here’s an example: message = [[That's Jack O'Neill, with two ll's]] If you used single quotes for enclosure in a scenario like this, you would get an error: message = 'That's Jack O'Neill, with two ll's' Likewise, you would also get an error using the following line, as the single and double quotes need to have a matching pair or be escaped. message = That's Jack O'Neill, with two ll's The correct way to declare the same would be to place a backslash before the literal quotes, like this: message = 'That's Jack O'Neill, with two ll's' or like this: message = That's Jack O'Neill, with two ll's
  • 16. CHAPTER 1: Introduction to Lua 8 You will notice that it is easy to miss that, in which case the interpreter will only spawn errors. In such cases, using the long brackets is very helpful. Lua also has levels of nesting with long brackets; you can have various levels by inserting an equal sign between the two opening brackets and one between the two closing brackets, like so: testmsg = [=[ One ]=] print(testmsg) You can use this for some very interesting-looking source code where you can use testmsg = [======[ One ]======] print(testmsg) -- Prints One Numerals Numbers can be expressed in Lua as decimals, floats, hexadecimals, and scientific notations. Here’s an example of each: print(5) -- 5 This is a decimal number print(5.3) -- 5.3 This is a floating point number print(5.31e-2) -- 0.0531 This is a scientific notation number print(0xfeed) -- 65261 This is a hexadecimal number Values and Types In languages like C, you have to define a variable with a particular type. For example, you might need define a variable i as an integer (int), like so: int i; With Lua, you do not have to define the type of variable; you can simply assign the value, and the value can change on the fly. In Visual Basic 6 (not to be confused with Visual Basic.NET), this type of variable was called a variant variable, and had to be explicitly defined as follows: dim i as variant In contrast, Lua stores variables in memory. Lua stores a variable’s value and type together. All variables in Lua are first-class values. This simply means that these values can be stored in variables, passed to other functions as arguments, and returned from a function. There are eight different types of variables in Lua, which I’ll describe next. nil This is the same as null. If you have a variable that holds a reference to the last-held value and the garbage collector doesn’t clean it up, you can set the variable to nil to indicate that the space referenced can be garbage collected.
  • 17. CHAPTER 1: Introduction to Lua 9 boolean boolean variables are our trusty true and false. These are used to check for conditions; however, it should be noted that both nil and false will result in the condition being false and any other value resulting in true. trusted = false if (trusted) then print(Yes) end -- Nothing is printed trusted = 1 if (trusted) then print(Yes) end -- Yes is printed trusted = nil if (trusted) then print(Yes) end -- Nothing is printed number number variables are numbers that can be expressed as decimals, longs, integers, hexadecimals, and floats. Lua saves the numbers as double-precision floating-point numbers. string Lua strings are generally 8-bit clean strings (i.e., they can hold any 8-bit character, including embedded zeros). Unicode variables are a slightly different matter, but are handled by Lua if the platform supports Unicode. function In Lua, functions can also be stored and passed as variables. This functionality of being able to store and pass functions as parameters makes the functions in Lua “first-class functions.” userdata This is a memory block that is allocated from C, allowing C functions to store and access data. userdata variables cannot be created or manipulated in Lua, but only through the C API. thread This is a special type of variable; this specifies an independent thread of execution. This is not the same as the operating system thread. table table variables are what we would call arrays, associative arrays, hash tables, sets, records, lists, trees, and even objects in Lua. Note Tables, functions, and threads do not really hold any values—only references to them.
  • 18. CHAPTER 1: Introduction to Lua 10 Code Blocks and Scopes In Lua, every variable has a scope, which means that it is accessible to the code depending on its life cycle as determined by the scope. Variables are either global or local. By default, variables are defined as global unless explicitly defined as local. In code, variables set between a do and an end block are not accessible outside of the block, and any local variables that are set outside of the block are accessible inside the block. Let us look at this with an example: i = 1 print(i = , i) do local i = 2 print(i = , i) end print(i = , i) Coercion is a simple term given to the process of converting a string into a number following the conversion rules (if possible) to provide arithmetic operations between a string and a number. one = 1 two = 2 print(one + two) -- 3 is printed In many languages, attempting such an arithmetic operation between two different data types (in this case a string and a number) would fail. In some other scripting languages, this code would instead add the value to the string, resulting in the string 12. However, in Lua, this outputs the value 3, where one is converted into numeric 1 and then added to the value of two to output 3. However, if we wanted to add the two strings 1 and 2 to get 12, then we would need to use what is called concatenation. In Lua the concatenation operator is the double-dot (..). This combines the two strings and returns a new string that contains the two strings passed. Lua Operators The operators in Lua can be grouped into different types of operators, which include arithmetic, relational, and logical operators, among others. Arithmetic Operators These do not need much of an introduction; they are simple and straightforward. Table 1-1 lists them.
  • 19. CHAPTER 1: Introduction to Lua 11 Relational Operators These are the operators used for comparing or conditions. They’re listed in Table 1-2. Table 1-1. Arithmetic Operators Operator Description + Addition - Subtraction * Multiplication / Division % Modulo ^ Exponent - Unary negation Table 1-2. Relational Operators Operator Description == Equality (to check for equality between two values) ~= Not equal to (the opposite of equality) Less than Greater than = Less than or equal to = Greater than or equal to These operators will always result in a true or a false return value. It should be noted that when comparing two numbers or values, use the == where as a single=in Lua signifies assignment. Logical Operators The logical operators in Lua are and or not The way the and and or work in Lua is by what’s called the shortcut evaluation. It checks for a value, and checks further only if it is required. and returns the first arguments if the value is false or nil; if it isn’t, then it returns the second argument. or, on the other hand, returns the first value if the result is not false or nil, and returns the second argument if the first argument is false or nil. The best use of or is in functions for assigning default values: a = a or 5 -- Can be used to assign the value of 5 if the value of a is nil or false
  • 20. CHAPTER 1: Introduction to Lua 12 We can test how these work as follows: testing = nil print(testing) print(testing and 5) print(testing or 5) print(not testing) testing = 15 print(testing) print(testing and 5) print(testing or 5) print(not testing) Other Operators Apart from the standard operators that we have discussed, there are a couple of other operators offered to us by Lua. They are used for operations like concatenation and obtaining the length of something; these two work with strings, though the # operator can also be used with arrays. Concatenation operator:  .. Length operator:  # As mentioned previously, the concatenation operator in Lua is the double-dot (..). It is used to add two strings together, like so: print(one, two, .. buckle my shoe) The length operator returns the length of the string. print(#this is a long string) -- prints 21 as the length of the string Summary The portability of Lua means that we can run our code on various devices and desktops. The small footprint of Lua and a very flexible and forgiving syntax allows for rapid prototyping and code testing. We have seen that Lua is increasing in popularity with game developers. In the next chapter, we shall take a closer look at the standard Lua libraries that provide all the commands that make up standard Lua.
  • 21. 13 Chapter 2 Lua Libraries In the previous chapter, you learned the reasons behind Lua and that Lua is, after all, made up of C code libraries. One of the advantages that the developers of Lua got from this architecture for Lua was that they could add functionality as required. Adding functionality involved writing new functions and making them available in Lua. It is quite a surprise that Lua does not have multiple distributions and remains as intended by the developers; there are not many modified versions. However, many developmental studios do modify, or rather adapt and customize, Lua for their own editors and tools. In this chapter, we shall look at the standard Lua libraries and namespaces that provide us with their functions. Then we’ll have a detailed look at the system- and table-related functions. Basic Functions Lua has some basic functions that are part of the Lua system, we’ll have a look at the following subsections. These form part of the core library and are generally available to most of the distributions. assert ( v [, message] ) This function is similar to the assert function used with C; it returns an error if the value of the argument v is false (either nil or false);. The message, if present, is displayed as an error; if absent, the default text “assertion failed!” is displayed. assert(money0,you need to have some money to buy something) collectgarbage ( [opt [,arg]] ) This function is a generic interface to the garbagecollector. The function acts differently depending on the parameter opt. The options that you can pass to this function as opt are
  • 22. CHAPTER 2: Lua Libraries 14  collect: Performs a full garbage-collection cycle. This is the default option.  stop: Stops the garbage collector.  restart: Restarts the garbage collector.  count: Returns the total memory in use by Lua.  step: Performs a garbage-collection step. The step size is governed by arg.  setpause: Sets arg as the new value for pause and returns the previous value of pause.  setstepmul: Sets arg as the new value for the step multiplier and returns the previous value for step. Tip If you want to know the memory usage of your app and clear up the memory and objects, you can force the garbagecollector to free up and reclaim the memory allocated and then print the amount of memory used after a cleanup by using the print(collectgarbage(count)) command. dofile ( [filename] ) You saw in Chapter 1 that Lua executes the code in chunks. This function opens the named file and executes its contents as a Lua chunk. When called with no arguments, it executes the contents from the standard input (stdin). It returns all values returned by the chunk. stdin is not available on iOS devices, and with CoronaSDK the function is sandboxed (i.e., disallowed). dofile(somefile.lua) error ( message [,level] ) This function terminates the last protected function and returns the message as the error message. error(This operations is invalid) _G This is not exactly a function, but a global variable. Lua does not use this variable, but it holds all the global variables and function. getfenv ( [f] ) This function returns the current environment in use by the function. The function f can be a Lua function or number.
  • 23. CHAPTER 2: Lua Libraries 15 getmetatable ( object ) This function retrieves the metatable associated with the object. It returns nil if there is no metatable present. This is mostly used to add functionality to an object table. In some cases, this is also used as a signature of the object. So while the type function does not tell you much, the metatables can be compared with a list of known metatable signatures to get more information. ipairs ( t ) This function returns a function that returns three values, an iterator function, the table t and 0. It works with the array tables only. The following code will iterate over the pairs up to the first integer key missing from the table: t = {1,2,3,4,test = test,5,6} t[3] = nil for i,v in ipairs(t) do -- body print(i,v) end load ( func [,chunkname] ) This function is similar to the dofile command; it loads a chunk using the function func. Each time the function is called, the function must return a string that concatenates with the previous result. When the chunk is complete, it returns nil and an error message. The chunkname is used for debugging. When the function is called and an error occurs, Lua displays debugging information, including the line number where the error occurred and the name of the Lua file in which the error occurred. When we have compiled chunks, there is no filename and hence, for debugging purposes, it is up to you, the developer, to provide that information in the form of the chunkname parameter. loadstring ( string [,chunkname] ) This function is similar to load, but instead of loading the compiled bytecode from a file, it takes the compiled code (chunk) from a string. loadstring(compiledChunk, OurChunk) next ( table [,index] ) This function allows the program to iterate through all the fields of a table. The function returns multiple values. Internally, the function takes on system commands. t = {One, Deux, Drei, Quarto} print(next(t, 3))
  • 24. CHAPTER 2: Lua Libraries 16 pairs ( t ) This function is used to iterate through the keys and values in a table. t = {one=Eins,two=Zwei, three=Drei} for k,v in pairs(t) do -- body print(k,v) end pcall ( f, arg1, … ) This function calls the function f with the arguments in protected mode. This means that any errors inside of the function f are not propagated outside of the function. print( … ) This function is the one that you will use most during development. It can receive any number of arguments, and it prints all of their values to stdout. It uses tostring and tonumber for conversion, and it provides an easy way to show a value quickly. However, it is not intended for formatted output. rawequal ( v1, v2 ) This function is used to check if the value v1 is equal to v2. It returns a Boolean indicating the outcome of the comparison. rawget ( table, index ) This function returns the value of table[index] without invoking any metamethod. The table must be a valid table and the index a non-nil value. This is equivalent to table[index] rawest ( table, index, value ) This function sets the value of table[index] without invoking any metamethods. The table must be a valid table and the index a non-nil value. This is equivalent to table[index] = value select ( index, … ) This function returns all of the arguments passed to the function starting with the argument after the index specified.
  • 25. CHAPTER 2: Lua Libraries 17 setfenv ( f, table ) This function sets the environment to be given to the function f. f can be a Lua function or a number that specifies the value of the platform. setmetatable ( table, metatable ) This function is used to set the metatable for any table. tonumber( e [,base] ) This function is used for converting between the numbers from string to numerical values. If the argument e is in a form that can be converted, it is converted and returned; otherwise, nil is returned. print( tonumber(42) ) print( tonumber(2A,16)) tostring ( e ) This function tries to convert the given argument to string format. If the passed parameter is a number, it is converted into a string. If it is an object and its metatable has a tostring function, the tostring function is called to convert the passed parameter. Note Lua converts between numbers and strings as required (and if possible). However, calling the tostring function is a way to tell Lua to convert the value into a string. Objects and tables are not automatically converted into strings; instead, the function tostring (if present) is called, which returns the string representation of the object/table. type ( v ) This function returns the type of the arguments, coded as a string. The possible results are nil, number, string, boolean, table, thread, and userdata. print(type(Hello World)) print(type(4)) print(type({})) unpack ( list [, i [, j] ] ) This function returns the elements from an array table. This function is equivalent to return list[i], list[i+1], ... , list[j]
  • 26. CHAPTER 2: Lua Libraries 18 Manually, this code can only be written for a fixed number of elements, and we cannot use a loop, as we have values to return. The parameter i specifies the start element and j specifies the last element, by default. (When these values are not provided, i is 1 and j is the length of the list as defined by the # operator.) local color = {255,255,255} function tableToParams(theTable) return unpack( theTable) end print( tableToParams(color)) _VERSION This is not a function, but a global variable. This holds the current interpreter version. print ( VERSION ) -- This will return the version of Lua in use xpcall ( f, err ) This function is similar to the pcall function, except that with this call, you can specify a new error handler. If there is an error inside of the function f, it is not propagated, and xpcall catches the error and in turn calls the err function with the original error object function spawnError() -- this function shall spawn an error local this=someFunctionNotDeclared() end print(xpcall(spawnError, function(err) print(Error:, err) return 1 end)) System Libraries The commonly bundled system libraries that you will end up using while working with Lua are  table  string  math  file  os The table namespace provides us with the functions related to array manipulation, as these functions are not applicable to hash arrays or associative arrays. This is explained in detail in the following section. The string namespace provides us with functions to deal with string manipulation. These allow for searching, splitting, and replacing strings, and are quite helpful for parsing and displaying information. We shall have a close look at the string namespace in Chapter 5.
  • 27. CHAPTER 2: Lua Libraries 19 The math namespace provides all the math-related functions; these are the basis for all the logic in most games. The math namespace provides all math-related functions that can help calculate things like where the player is, where the objects are, whether the player won or lost, and much more. We shall look at this namespace in detail in Chapter 4. The file namespace, covered in Chapter 3, provides file-related functions, including those that allow the user to read, write, and delete files. Note that file operations do not include much file system–related functionality, and there is a third-party library called Lua File System (LFS) that offers the missing functionality. The os namespace provides functions that are related to OS-specific functions, including functions that deal with things like time, date, and locale. We shall look into this further ahead in the “OS Functions” section of this chapter. The way to use these libraries is to prefix the library name followed by a dot and the function. This is a good way of separating the functionality available in the library from the common or global area. With libraries, variables and functions can be part of the namespace. For example, if we had a function a1, and the namespace myFunc had a function defined as a1, these two would be completely different functions. To access these functions, simply add the namespace as a prefix in front of the function name, as follows: -- call the global a1 function a1() -- calling the a1 function available in the namespace myFunc myFunc.a1() Note There is no function called a1, so these commands will not work; these are just for illustration purposes. Table Functions You may have already noticed that in Lua, if anything is not a string or a number, then it is an object (i.e., a table). Tables are the most important data type in Lua. There are a handful of functions to manipulate end work with the tables. These are useful functions for working with array-type tables. The functions available are described in the following subsections. table.concat ( aTable [,sep [,i [,j] ] ] ) This function returns the elements of an array (if they are either strings or numbers) concatenated as a string. These are separated by a separator, as indicated by sep, which is a blank string by default. If no parameters are passed for i and j, then i is the first element and j is the length of the table. If i is larger than j, then an empty string is returned. If you were to write this function yourself, it would look like return aTable[i]..sep..aTable[i+1] ... sep..aTable[j]. local aryTable = {1, deux, 3, vier, 5} print( table.concat( aryTable, ,, 1,3)) print(table.concat(aryTable))
  • 28. CHAPTER 2: Lua Libraries 20 table.insert ( aTable, [pos,] value ) This function is used to insert a value into the array table, as indicated by aTable. The value is inserted at the position indicated by pos; if no value is indicated for pos, then it is assigned the default value of the length of the table plus 1 (i.e., at the end of the table). local aryTable = {1, 3, 4, 5} table.insert(aryTable, 2, 2) print(table.concat(aryTable, ,) table.insert(aryTable, 6) print(table.concat(aryTable, ,) table.maxn ( aTable ) This function returns the largest positive numerical index of the given array table. Remember from Chapter 1 that the # operator returns the length of an array, but only of a contiguous section. So, if in a program you added values to the indices in a nonserial manner (i.e., not continuous), then the # operator would return the length as the block that was continuous. table.maxn, on the other hand, iterates through all the elements and returns the largest numerical index. local aryTable = {1,2,3,4,5} print(#aryTable, table.maxn(aryTable)) aryTable[10]=10 print(#aryTable, table.maxn(aryTable)) aryTable[25]=25 print(#aryTable, table.maxn(aryTable)) table.remove ( aTable [, pos] ) This function is like insert, but with the difference that it removes an element from the array table and returns the element being removed. In both insert and remove, the elements are shifted to accommodate the new index as required. The default position for pos is the length of the table (i.e., the last element). local aryTable = {1, 2, 3, 4, 5} table.remove(aryTable, 2, 2) print(table.concat(aryTable, ,) table.remove(aryTable) print(table.concat(aryTable, ,) print(aryTable[3]) table.sort ( aTable [, comp] ) This function is very useful when working with a series of values that need to be sorted. When no comp is specified, it uses the standardLua operator to compare two values, which works fine with numeric values. However, there could be situations where you might need to sort multidimensional arrays or arrays that contain non-numeric data. For such cases, the comp function is used. comp receives two table elements and returns true when the first is less than the second.
  • 29. CHAPTER 2: Lua Libraries 21 local aryTable = {4,7,1,3,8,6,5,2} print(table.concat(aryTable, ,)) table.sort(aryTable) print(table.concat(aryTable, ,)) Note These functions can be used only with array-type tables and are available in the table namespace. In order to use these functions, you need to prefix them with table. OS Functions There are a few functions that are available to interact with the OS; these can be found in the os namespace and hence are prefixed with os. The following subsections describe how they’re used. os.clock ( ) This function returns the approximate CPU time used by the program, in seconds. Every time some code is executed, this is incremented with the amount of CPU time used by the code. print(os.clock()) --0.030148 (could be different on your system) print(os.clock()) --0.030250 (could be different on your system) Note This does not return the time from the system clock; this is just the total CPU time used. os.date ( [format [,time] ] ) This function returns a string or a table containing the date and time, formatted as specified by the given string format. If no parameters are passed, it returns the string containing the current date and time based on the host system and the current locale. If the format is *t, then the function returns a table with the following fields:  year (four digits)  month (1–12)  day (1–31)  hour (0–23)  min (0–60)  sec (0–60)  wday (1–7, beginning with Sunday)  yday (day of the year; 1–366)  isdst (Boolean indicating if daylight saving time is in effect)
  • 30. CHAPTER 2: Lua Libraries 22 os.difftime ( t2, t1 ) This function returns the difference in the number of seconds between t2 and t1. os.execute ( [command] ) This function is the equivalent of the C system command. It executes the command passed in the OS shell. It also returns the status code, which is very much system dependent. This is not applicable on iOS, as it would be sandboxed and not execute. os.exit ( ) This function calls the C function exit, which terminates the application. Though this works on iOS devices, it should not be used. Any app that exits in this manner is considered to be an app that has crashed. The only way to exit an app should be when the user explicitly presses the Home button to exit the app. You can run the risk of Apple rejecting your application if it uses this function. Having said that, there are a couple of apps that have managed to slip under the Apple radar and exit an app in this manner (and the experience is indeed that of when an app crashes). os.getenv ( varname ) This is not applicable on iOS devices. os.remove ( filename ) This function deletes a filename or directory with the given name. The directories are removed if they are empty. If the function fails, it returns nil and a string describing the error. This will work only on the directories and files that you can work with (i.e., the ones in the Documents directory on an iOS device). The other directories are sandboxed and unavailable. os.rename ( oldname, newname ) This function renames a file or directory with the given oldname to the newname. If the function fails, it returns nil and a string describing the error. This works only with files in the Documents directory. Note The reason this works with files in the Documents directory is that most of the other directories are sandboxed or restricted from use. Any command that tries accessing the restricted directories will fail and do nothing. os.setlocale ( locale [,category] ) This function is not available in the context of iOS devices.
  • 31. CHAPTER 2: Lua Libraries 23 os.time ( [table] ) This function returns the current time when called without arguments. The table passed as parameters should have the fields set to at least year, month, and day. Other fields, such as hour, min, sec, and idist, are optional. os.tmpname ( ) This function returns a string with a filename that can be used for a temporary file. This file needs to be explicitly opened and explicitly removed when not required. This is different from an io.tmpfile function (discussed in the next chapter), which automatically removes the file when the program ends. Tables: A Quick Overview I have noted that tables are one of the many types of variables available in Lua. Though it might sound trivial, tables are the backbone of Lua, and they’re used in many ways: as arrays, hash tables (associative arrays), and objects, and in plenty more. The following subsections will discuss tables as arrays and hash tables. Tables As Arrays The Lua equivalent of an array is a table. All arrays in Lua have an index base of 1, which means that the first entry starts at 1 (not 0, as in many other languages). Arrays need to have a numeric index. These can be multidimensional and do not need to be dimensioned at declaration. These can grow and be redimensioned at runtime. local theArray = {} for i = 1, 10 do theArray[i] = item . . i end Tables As Associative Arrays Tables are the Lua equivalent of associative arrays, hash tables, and even NSDictionary objects. The difference between an array and an associative array is that, instead of having a numeric index to access an element of the array table, an associative array can use a string to access the elements. local theTable = {} for i = 1, 10 do theTable[item..i] = i end Note Lua is very flexible and hence is very forgiving, even if you mix the two types of arrays.
  • 32. CHAPTER 2: Lua Libraries 24 local theMixedTable = {} for i = 1, 5 do theMixedTable[i] = item .. i end theMixedTable[name] = mixedTable theMixedTable[subject] = coding print(theMixedTable.name, theMixedTable[3]) Functions: An Advanced Look In the previous chapter we had a look at functions and how Lua sees them. Lua objects and structures are Lua tables, and the good part is that tables can hold functions and other tables, string, and numbers. In effect each object with a function is like a namespace that has its own set of functions. To access the function of a particular object, you need to access the function with the namespace prefixed. myObj = { type = furry, name = Furry 1, description = Fluffy furry teddybear, display = function () print(description) end } myObj.show = function() print(Now Showing...) end To call the function, you use the following: myObj.display() myObj.show() Tables As Objects As you’ve seen, tables can be used as objects. In this next example, we’ll create an object called myObj that has properties of type, name, description, and so on. In this example, you’ll create a game that spawns a series of animals, each with different strengths and different functions for movement. Since some of the functions might overlap, in order to avoid writing the same code over and over again, you’ll create a new object based on the parent object, such that all of the functions are available to this object. (We shall create such objects later in the book.) So, when this object is passed, you can simply invoke the move function that is common to the animals, but might be specific to each of the animals depending on its type.
  • 33. CHAPTER 2: Lua Libraries 25 One way to manage this is as follows: local cat 01 = animal.new(cat) local mouse 01 = animal.new(mouse) animal.move(cat 01) animal.move(mouse 01) This might work for some; however, an alternative method to manage this would be the following: local cat 01 = animal.new(cat) local mouse 01 = animal.new(mouse) cat 01:move() mouse 01:move() Further, if you had this in an array of animals, you could just about as easily have something like this: local i for i=1,#aryAnimals do aryAnimals[i]:move() end Or you could very well also use something like aryAnimals[i].move(aryAnimals[i]) Notice here how the function is invoked using the dot (.) or the colon (:). This is something a lot of beginning Lua developers come across, and they often have questions about the difference between, say, cat 01:move() and cat 01.move(). The following section will describe the differences. The Difference Between . and : In the preceding example, there’s no difference between calling cat 01.move() and cat 01:move(). But let’s consider that in the same function we also need to pass a parameter speed, which indicates how fast the animal should move. So we simply pass the speed as a parameter as cat 01:move(10) or cat 01.move(10) This on the face of things seems right, but will produce two very different results. The reason is that when we use the ., we are telling Lua to invoke the function that is a member of the object (table), and when we use the :, we are telling Lua to do this and we’re also passing the function an unseen parameter of itself. So when we call the function with :, we are passing it two parameters: the first being the object itself and the second being the speed. With the . method, on the other hand, we pass it only one, which is the speed. Let’s look at how it is defined in code (see Figure 2-1).
  • 34. CHAPTER 2: Lua Libraries 26 Notice that the functions are declared differently, but the output of both is the same. In short, you can say that obj:func() is the same as calling obj.func(obj). Figure 2-1. The output of the function in Lua running in the terminal Note It is very easy to forget about the way you might have declared the function and hence end up calling it a different way, which can cause some hiccups in your code where a parameter passed would get shifted and give you strange results. To avoid that, keep a consistent method of declaring and calling functions. From that last example, one question that might come to mind is, When do you use a single dot (.) and when do you use a colon (:) if Lua is not an object-oriented language? Why would you ever need that? In order to answer these questions, let’s work on an object and give it some functionality. This sample doesn’t use objects or external files, so it can be run in the Lua interactive console without any problems.
  • 35. CHAPTER 2: Lua Libraries 27 function newAnimal(name) local animal = { name = unknown, says = pffft, position = {x = 0,y = 0}, } animal.name = name if name==cat then animal.says = meow elseif name==dog then animal.says = bow wow elseif name==mouse then animal.says = squeak end function animal:speak() print(animal.says) end function animal:move(speed) animal.position.x = animal.position.x+speed end return animal end Now we can create a new instance of an animal by simply calling cat 01 = animal.new(cat) cat 01:speak() This is perfectly fine as an example that creates a new object every time it is invoked. However, this is also how many beginners would code—note that in the functions, while we are passing the object via self, we are not using it, and we are still referencing it by the fixed animal table that we created. This can cause a bit of grief later on if it’s not checked right at the start. The way to avoid this being a problem in the future is to replace the namespace with the object referenced as self instead. The modified code would look like the following: function newAnimal(name) local animal = { name = unknown, says = pffft, position = {x = 0,y = 0}, } animal.name = name if name==cat then animal.says = meow elseif name==dog then animal.says = bow wow elseif name==mouse then animal.says = squeak end
  • 36. CHAPTER 2: Lua Libraries 28 function animal:speak() print(self.says) end function animal:move(speed) self.position.x = self.position.x+speed end return animal end This would work fine and not cause issues. cat 01 = animal.new(cat) cat 01:speak() cat 02 = animal.new(dog) cat 02:speak() When we run the code, the functions get the object passed rather than the Animal namespace. This also ensures that the variables that are modified are specific to the object rather than the ones in the Animal namespace. That will thereby eliminate the issues mentioned earlier. Summary This chapter focused on functions and tables, the building blocks of Lua programming. It’s important to remember that everything that is not a string, a number of boolean is a Table. Tables are very powerful and important in Lua. You’ll be reading a lot about them (in some form or other) in most of the chapters. Another important concept that we touched upon is the namespace. Namespaces help to distinguish between the functions available in the main namespace (the global functions) and the functions in a custom library.
  • 37. 29 Chapter 3 File Operations When creating an app or a game, you need file I/O (input/output). You may not be working with a database, but there will always be the need to save something back to the disk; it could be the levels, the high score, a character the player might have unlocked, or some information regarding in-app purchases. So, let’s first look at what we have available in terms of functions that offer file operation functionality. Lua has two sets of functions for file operations, one called implicit and the other explicit. The difference between the two is that implicit functions work on the default file as provided by the io namespace, whereas explicit functions work with a file handle provided from a previous operation, such as io.open. Implicit Functions This section lists and describes the implicit functions you’ll be using in your Lua programming work, accompanied by a short example of how each is used in code. io.close ( [file] ) This function closes the output file; it is similar to file:close(), but when no file is passed, it closes the default output file. You can see how io.close is used to close a fileHandle. To confirm, we print the type of fileHandle to check if the file is open or closed. fileHandle = io.open(file.txt, w) print(io.type(fileHandle)) fileHandle:write(Hello world) io.close(fileHandle) print(io.type(fileHandle))
  • 38. CHAPTER 3: File Operations 30 io.flush ( ) This function runs file:flush() on the default file. When a file is in buffered mode, the data is not written to the file immediately; it remains in the buffers and is written when the buffer nears getting full. This function forces the buffers to write to file and clear up. io.input ( [file] ) This function returns the current default input file when called without any parameters. The parameter passed can be either a filename or a file handle. When the function is called with a filename, it sets the handle to this named file as the default input file. If it is called with a file handle, it just sets the default input file handle to this passed file handle. io.lines ( [filename] ) This function opens a given filename in read mode and returns an iterator function that returns a new line from the file every time it is called. When the iterator function detects that the end of the file has been reached, it closes the file and returns nil. When io.lines is called without a filename, it is equivalent to io.input():lines(), and it reads from the default input file and does not close the file when the end is reached. Here’s a way to access this function: for line in io.lines(filename) do print(line) end io.open ( filename [,mode] ) This function is the main function that you use in reading and writing files with Lua. The mode is a string value that can be one of the following:  r: Read mode (default).  w: Write mode.  a: Append mode.  r+: Update mode. All previous data is preserved.  w+: Update mode. All previous data is erased.  a+: Append update mode. All previous data is preserved and writing is only allowed at the end of the file. The mode can also have a b at the end to indicate that the file is to be opened in binary mode rather than in text mode. This function returns a file handle that can be used in explicit file operations. file = io.open(myfilename.txt, r)
  • 39. CHAPTER 3: File Operations 31 io.output ( [file] ) This function is similar to io.input but operates on the default output file instead. Using this function, you can redirect the output to the file you want. Here’s an example of how it’s used: oldIOFile = io.output() io.output(mynewfile.txt) io.write(Hello world) io:output():close() io.output(oldIOFile) io.read ( … ) This function is equivalent to io.input():read(). print(io.read()) io.tmpfile ( ) This function returns a handle for a temporary file; the file is opened in update mode and removed automatically when the program ends. fh = io.tmpfile() fh:write(Some sample data) fh:flush() -- Now let's read the data we just wrote fh:seek(set, 0) content = fh:read(*a) print(We got : , content) io.type ( obj ) This function returns the result if the handle specified by obj is a valid file handle. It returns the string file if obj is an open file handle and the string closed file if obj is a closed file handle. It returns nil if obj is not a file handle. print(io.type(fh)) – prints nil as fh is nil fh = io.input() print(io.type(fh)) io.write ( … ) This function is equivalent to io.output():write(). io.write(Hello World)
  • 40. CHAPTER 3: File Operations 32 Explicit Functions This section lists and describes the explicit functions you’ll be using in your Lua programming work. file:close ( ) This function closes the file that is referenced by the file. file = io.open(myFile.txt, w) file:write(Some Data) file:close() file:flush ( ) This function saves any data that is not as yet written (in the buffer) to the file. fh = io.tmpfile() fh:write(Some sample data) fh:flush() file:lines ( ) This function returns an iterator function that returns a new line from the file every time it is called. It is similar to io.lines, with the difference that this function does not close the file when the loop ends. local file = io.open(filename) for line in file:lines() do print(line) end file:close() file:read ( [format] ) This function reads data from the file according to the given format. By default, read reads the entire next line. The formats that are available for reading are  '*n': Reads a number; returns a number instead of a string  '*a': Reads the whole file starting from the current position  '*l': Reads the next line; returns nil when the current position is at the end of the file (default format)  number: Reads a string of characters as specified by the number, returning nil at the end of the file. Following are some examples of using these: local filename = data test.txt local file = io.open(filename)
  • 41. CHAPTER 3: File Operations 33 local contents = file:read(*a) file:close() print(Contents of the file:, contents) If this file were opened in binary mode and we needed to get only a particular number of characters, then we would use it as follows: local filename = test.zip local file = io.open(filename,rb) local contents = file:read(2) file:close() print(File Header:, contents) -- All ZIP files have the starting two characters as PK file:seek ( [whence] [, offset] ) This functions sets and gets the current file position. whence is a string value that can be any of the following  'set': The base position 0 (beginning of the file)  'cur': The current position (default value)  'end': The end of the file The offset value passed is measured in bytes from the base specified as per one of these three options. file:seek is one of most important functions when working with binary files and fixed formats; it allows the developer to iterate back and forth to overwrite or update certain portions of the file. fh = io.tmpfile() fh:write(Some sample data) fh:flush() -- Now let's read the data we just wrote fh:seek(set, 0) content = fh:read(*a) print(We got : , content) file:setvbuf (mode [, size] ) This function sets the buffering mode for an output file. There are three buffering modes available in Lua, and their values are passed as strings:  'no': No buffering is set, so the output of any operation appears immediately.  'full': Full buffering is set, so the output operation is only performed when the buffer is full. You can force a flush to write the buffers.  'line': Line buffering is set, so the output is buffered until a newline character (Enter) is found. io.output():setvbuf(no)
  • 42. CHAPTER 3: File Operations 34 file:write( … ) This function writes to the file each of the arguments passed to the function. The arguments must be either strings or numbers. To write other values, you might have to convert them to string format. file = io.open(myfile.txt,w) file:write(Writing to a file) file:close() Note The pure implementation of Lua lacks the functions and commands required for file system access. This is generally available as an external library that can be added. It is called Lua File System (LFS). As of this writing, you can integrate it with all frameworks (the amount of effort this takes, however, depends on the framework.) Uses of File I/O in Gaming Though this is a no-brainer, there are so many reasons why you might want to read or write data from the storage. It can be for little things like level-related data and high scores, or for complex things like saving the state of the game with the entire inventory, units, and so on. In the game, the onus is on you to save and load the data to help provide continuity and seamless game play to the player. Let’s look at how we would do that when dealing with stuff like life, health, score, level, and so forth. Saving a Variable In many games, you generally get only about three lives. So, consider the following code: local lives = 3 print(You have .. lives .. lives left) There are many ways of dealing with this. One good way would be to save the data as soon as you change it—something like an autosave option. So, let’s write out lives variable to the storage so that it persists. function writeToFileSingle(value, filename) local hfile = io.open(filename,w) if hfile==nil then return end -- Did not get a handle on the file hfile:write(value) hfile:close() end In the preceding code, we declare a function called writeToFileSingle that takes two parameters: value and filename. The function opens a file, writes the data to the file, and then closes the file.
  • 43. CHAPTER 3: File Operations 35 If we open a file, we are responsible for closing it too. When we try to open a file using the io.open function, it returns the file handle and a string that contains the reason for the failure (if it fails to open the file). To save our value using this function, we simply call writeToFileSingle(score, score) writeToFileSingle(health, health) and so on. Congratulations, you have now written code to save a variable, and it can be run in the interactive Lua shell, as expected. Note Irrespective of which platform you choose as a developer, the preceding Lua code should work across most of the platforms and Lua frameworks. Grabbing the Data In addition to saving data, we also need to retrieve it. In a game, dumping data that we cannot retrieve is as good as not saving any data at all. We have, with the earlier function writeToFileSingle, saved our data to a variable. Now comes the tricky part: reading the values from the file. In theory, reading the data from a file should be the reverse process of writing to the file. So, we open the file that we have saved our data into and then we read all of the data from the file. function readFromFileSingle(filename) local hfile = io.open(filename, r) if hfile==nil then return end local value = hfile:read(*a) hfile:close() return value end Since we’ve saved our data using the writeToFileSingle function, we can retrieve our data easily, like so: print(readFromFileSingle(score)) print(readFromFileSingle(health)) Note Since the data is one piece of information per file, the order in which you save it and the order in which you load it shouldn’t matter. If the file does not have any data, it just returns nil, which pretty much means the same and can be managed if required.
  • 44. CHAPTER 3: File Operations 36 How the Code Works It is rather easy. Most of the code is similar to what we used in writeToFileSingle, which involves opening a file, but in read mode instead. (If you do not specify a mode while opening a file to read, the default mode is read mode). Then we use the read function with the *a parameter to read the entire contents of the file. This is fine for this scenario, as we only have a small amount of data to read. Then we close the file and return the data read from the file. Potential Issues These two functions work well for loading and saving data. But, as mentioned, it’s not good to have a file for each piece of data that we want to save; it would be better to have a single file than multiple files with scraps of data in them. So, the next possible option is to save all of the data in a single file. Doing so isn’t much different than what we did in the preceding code. The difference is that we save multiple values to the file, like so: function readFromFile(filename) local results = {} local hfile =io.open(filename) if hfile==nil then return end for line in hfile:lines() do table.insert(results, line) end return results end There are a couple of differences in this code as compared to the earlier code. The first is that we use an array table called results to store everything we read from the file. The next is that instead of using hfile:read(*a) to read the content, we use hfile:lines() to get one line at a time from the file. The newline character (Enter) separates the data and is the delimiter between the two lines. Once we get this data, we store it into the array results by using the table.insert function to add the data to the end of the table. Once we get the array returned to us, the positioning of the data is important. The positions of the data shall be fixed, so we need to know in advance what position coincides with what data. Saving Data to a Variable Here’s a quick tip on how to manipulate global variables. In Chapter 2, you read about a variable G, which is actually a table object and holds all the global variables, functions, and so on. When we declare a variable (without local scope), it is assigned to this table as a global variable. What we are going to do in this quick exercise is declare a global variable, read the value of the variable, and then manipulate it using the G table. myVar = 1 print(myVar) myVar = myVar + 1 print( G[myVar])
  • 45. CHAPTER 3: File Operations 37 G[myVar] = G[myVar] + 1 print(myVar) G.myVar = G.myVar + 1 print(myVar) How the Code Works We start our code with declaring a global variable called myVar and assigning it a value of 1, and then we print it to the screen. Next we increment it by 1 using myVar=myVar+1. This time we print the value again, but instead of using print(myVar), we access it directly from the global table G via print( G[myVar]). Then we increment the variable by 1 again but using G[myVar] and print the value using print(myVar). Lastly, we increment the value again by 1, but this time we access it using the G.myVar method to access the value and print the results. The idea of this exercise is to demonstrate how Lua uses global variables and how they can be accessed using G. Note Though global variables can be accessed in this manner, it is suggested that local variables be used instead; this reduces the number of variables used, saves on stack memory, and also had a speed advantage over global variables. Back to our saving and loading of data, we want to consolidate our data into one file so that we can read our data in one go. In our modified version, we are reading the data into an array called results. The only issue is that to access the values, we need to access the data by the numbered index—but how would we know what each numeric index corresponds to? Let’s try to read the data and also set the global variables with the values. function readFromFile(filename) local results = {} local hfile = io.open(filename) if hfile==nil then return end local lineNo = 0 for line in hFile:lines() do table.insert(results, line) lineNo = lineNo + 1 if lineNo == 1 then G[score] = line elseif lineNo == 2 then G[lives] = line elseif lineNo == 3 then G[health] = line elseif lineNo == 4 then G[level] = line end end return results end
  • 46. CHAPTER 3: File Operations 38 This is more or less what our code looked like earlier, only we have added a variable called lineNo and we keep incrementing it based on the lines read. When lineNo is 1, we save the value we have read into the variable score. Then we save lineNo 2 into lives, and so on, till lineNo is 4, after which (if there are more lines) we just don’t read them. Potential Issues In your app, the number of variables that you might store could be different for each application. You would never know the order in which your data is saved, and if the order of saving the data or reading the data is changed, you might have values that end up in the wrong variables. Most importantly, it would be near impossible to set up multiple if .. then statements to load the variables, not to mention the names for those variables. So what we are going to do to fix this issue is have a table with the data and field names in it. This will provide us with the flexibility to expand this further in the future. function readFromFile(filename,resTable) local hfile = io.open(filename) if hfile == nil then return local results = {} local a = 1 for line in hfile:lines() do G[resTable[a]] = line a = a + 1 end end We read through the data one line at a time, and with each loop, we increment the index variable a. We store the value that we have read into a global variable with a name specified in the array. For example, if we had specified in our array that we wanted the values to be Line1=Score, Line2=Lives, and Line3=health, then the function will automatically create global variables with these names and assign the value to them. This function will now read the data, save it into the array table, and access it via the global variable. However, we need to pass it the table that is modified for this. local aryTable = { Score, Lives, Health, } We call the function simply as follows: readFromFile(datafile, aryTable) This method has its own set of problems. What if we were to add some data in aryTable not at the end, but in the middle? This would make the variables all mixed up and in the wrong places. So how do we fix that? There are many easy ways to approach this issue, and each has its own set of pros
  • 47. CHAPTER 3: File Operations 39 and cons. However, the best method would be to get the name of the variable and the value of the variable from the file. Writing Data to the File We have written some code to read our data from the file. Now we’ll write some code to write the data, which could be read using the preceding function. function writeToFile(filename, resTable) local hfile = io.open(filename, w) if hfile == nil then return end local i for i=1, #resTable do hfile:write( G[resTable[i]]) end end The code for writing the data to the file is not very different. We open the file in write mode, and then we iterate through the list of variables that we want to save to the file. These are found from the resTable parameter passed. So, whatever we have in this table, the function shall attempt to save those variables to the file. Saving a Table We just saved data that is in the form of either strings or numbers. If the data to be saved is anything else, the functions will start to fail, and more so if the variable is a table. The biggest issue with tables is iterating through the depths of the table. If you were to use any other programming language, you would hear, “Why not serialize the data?” I’ll explain why this isn’t a good idea in Lua. The mark of good developers is their ability to avoid reinventing the wheel, instead spending their time with things that warrant their focus. Lua has a third-party Lua library that allows you to use JSON in your Lua projects; this library can help encode or decode the information between the table object and a JSON-encoded string, like so: local json = require(json) local theTable = { title = Learn Lua for iOS game development, author = Jayant Varma, publisher = Apress, eBook = true, year = 2012, } local resString = json.encode(theTable) writeToFileSingle(restring,mytable) local readString = readFromFileSingle(mytable) local resTable = json.decode(readString) for k,v in pairs(resTable) do print(k,v) end
  • 48. CHAPTER 3: File Operations 40 When you run this code, you will see that we save the data we create as a string to a file called mytable. In the example, we read the data back and decode the JSON-encoded string to an expanded Lua form table. Then we list the fields available in that table to prove that the code works. Note Though this code is completely valid, if you run the code in the Lua interactive shell, you might face issues such as error messages, as there is no json.lua file in the path. Dynamic Variables How do I create dynamic variables? is one of the most commonly asked question by many developers, especially ones that are beginning their journey with development. Some beginner developers use variables as follows: Object1 = Apple Object2 = Ball Object3 = Cat Object4 = Dog In this code, the developer wants to create a series of such variables dynamically and be able to access them by specifying the last digit, so the access expected would be number = 3 print(Object .. number) and the expectation is that it should output Cat. However, what it outputs is Object3. Most beginning developers assume that it should have worked as expected. If you need to access the variable in this manner, it is not by creating multiple variables. The proper way to do so is to create an array. The array can be accessed by passing it the number as we expected to do. Objects = {Apple, Ball, Cat, Dog} number = 3 print(Objects[number]) This works perfectly fine for what we need. This time around we see the output Cat. Summary In this chapter you learned about the implicit and explicit functions relating to file I/O. You also saw how to read and write data as singular values, and how to write an entire table of data onto the storage space on the device. Files are good for saving scraps of data; however, when you need to access larger amounts of data, it would be better to use a database. In the next chapter we shall look at the math namespace, which offers functions that we can use to do all of the calculations required for our apps.
  • 49. 41 Chapter 4 Math with Lua Love it or hate it, if you have decided to be a developer, you will have to come face to face with math. It is indeed surprising to see how many students dislike or shy away from math, but it just comes back to us in some form or the other, irrespective of our profession. An accountant needs to look at the accounts and add them up (requiring math), a surveyor needs to apply trigonometric principles to get elevation and terrain information, a banker needs to calculate interest and yield for investments, and so on. It reminds me of Homer Simpson, who once said, “English? Who needs that? I’m never going to England!” However, you have decided to be a developer, and you will come back to this time and time again, as many of the things that you need to do are based on simple math principles. These can be applied with any framework or language. Introduction to Math in Lua There is a system library included with Lua that offers a series of math functions. The following is a list of the functions available. Most of these functions are self-explanatory. math.abs (x) This returns the absolute value of x. If you pass this function a negative value, it returns the positive value of x. print(math.abs(−10)) -- Will return 10 math.acos (x) This returns the arc cosine of the value x in radians. print (math.acos(1)) -- Prints zero '0'
  • 50. CHAPTER 4: Math with Lua 42 math.asin (x) This returns the arc sine of the value x in radians. print(math.asin(1)) -- Prints 1.5707963267949 math.atan (x) This returns the arctangent of the value x in radians. This is in the range of –pi/2 to pi/2. print(math.atan(1)) -- Prints 0.78539816339745 math.atan2 (y,x) This returns the principal value of the arctangent of the quotient of the two numbers passed. print(math.atan2(1, 0)) -- pi/2 print(math.atan2(−1, 0)) -- -pi/2 print(math.atan2(0, 1)) -- 0 print(math.atan2(0, -1)) -- pi Note The parameters passed are y and then x, not x,y, as are generally passed. math.ceil (x) This returns the integer value of the passed value of x closest to the next integer. print (math.ceil(0.1)) -- Returns 1 print (math.ceil(0.5)) -- Returns 1 print (math.ceil(0.6)) -- Returns 1 math.cos (x) This returns the cosine value of x passed in radians. print(math.cos(1)) -- 0.54030230586814 math.cosh (x) This returns the hyperbolic cosine of a value. print(math.cosh(1)) -- 1.5430806348152
  • 51. CHAPTER 4: Math with Lua 43 math.deg (x) This function converts a value from degree to radians. print(math.deg(math.pi)) -- 180 math.exp (x) This returns e, the base of natural logarithms raised to a given power. print (math.exp(2)) -- 7.3890560989307 math.floor (x) This returns the lower integer value from the passed value of x. print (math.floor(0.1)) -- 0 print (math.floor(0.5)) -- 0 print (math.floor(0.9)) -- 0 math.fmod (x) This returns the remainder of the division of the arguments that rounds the quotient toward zero, according to the following equation: remainder=numerator – quotient * denominator The function itself is used like this: print(math.fmod(7.5,3)) -- 1.5 math.frexp (x) This function splits the value into a normalized fraction and an exponent. The results are two numbers. The number x can be represented as follows: fraction * 2^exponent Here are some examples of the function in code: print(math.frexp(2)) -- 0.5 2 print(math.frexp(3)) -- 0.75 1 print(math.frexp(1)) -- 0.5 1 math.huge This is a constant than a function; it returns inf, which is a very large number. print(math.inf)
  • 52. CHAPTER 4: Math with Lua 44 math.ldexp (m, e) This returns a number generated from the combination of the mantissa m and the exponent e. The formula used is number=m * 2^e Here’s the function in use: print(math.ldexp(0.5, 8)) -- 128 math.log (x) This returns the natural logarithm value of x. print(math.log(0.5)) -- (−0.69314718055995) math.log10 (x) This returns the base 10 logarithm value of x. print (math.log10(0.5)) -- (−0.30102999566398) math.max (x, …) This returns the maximum value among the passed values. print(math.max(2,5,3,8,3,4,5)) -- 8 math.min (x, …) This returns the minimum value among the passed values. print(math.min(2,5,3,8,3,4,5)) -- 2 math.modf (x) This returns the integer and the fractional part of the number passed. So, if we passed it x.y, it would return x and y. print(math.modf(3.75)) -- 3 0.75 math.pi This returns the math constant of pi. print(math.pi) -- 3.1415926535898
  • 53. CHAPTER 4: Math with Lua 45 math.pow (x,y) This returns the number that is the result of raising the number x to y (i.e., xy ). print(math.pow(3,3)) -- 27 = 3^3 print(math.pow(5,2)) -- 25 = 5^5 math.rad (x) This returns the angle x converted into radians. print(math.rad(math.pi)) -- 3.1415296535898 math.random ( [m [,n]] ) This returns a random value in the range between m and n. If the values of m and n are not passed, then the function returns a value between 0 and 1. If a single value is passed to this function, then an integer value between 1 and this number is returned. print(math.random()) -- A decimal value between 0 and 1 print(math.random(10)) -- An integer value between 1 and 10 print(math.random(5,25)) -- An integer value between 5 and 25 math.randomseed (x) This sets the seed for the random number generator. If you seed the value, you can get the same random values. math.sin (x) This returns the sine of an angle passed in radians. print(math.sin(30)) -- (−0.98803162409286) math.sinh (x) This returns the hyperbolic sine of a value. print(math.sinh(1)) -- 1.1752011936438 math.sqrt (x) This returns the square root of the number specified by x. print(math.sqrt(144)) -- 12 print(math.sqrt(9)) -- 3
  • 54. CHAPTER 4: Math with Lua 46 math.tan (x) This returns the tangent of the angle passed in radians. print (math.tan(45)) -- 1.6197751905439 math.tanh (x) This returns the hyperbolic tangent of a value. print(math.tanh(1)) -- 0.76159415595576 Practical Uses of Math in Gaming If you develop games, you will be surrounded with math. The simplest scenario that any game will involve is moving a character, and that involves moving the character on the x- or y-axis, or in plain terms, moving it left and right or up and down. This movement of the character left and right is said to be on the x-axis, and the up-and-down movement is on the y-axis. Another example where you would use math is simple scorekeeping, in which you increment the score by a value based on what object you might collect in the game. You would also use math to handle players with multiple lives, whereby a value is decreased every turn until it reaches zero, after which the game is over. But first, let’s brush up on a few basics about math (even though we all learned it in school). Assignment The first thing that we shall look at is assignment. Remember the school days when we had let x equal 5 let y equal 3 x+y=5+3 = 8 This concept remains even today. With Lua, when we assign a variable a value, this value can be one of the eight basic types discussed in the Chapter 1. The most commonly used ones are numbers, strings, and tables. The preceding algebraic equation would translate to the following: x=5 y=3 print( x+y= .. x+y) Increasing and Decreasing If you are coming to Lua from a C/C++ background, you may be used to operator overloading. This is why a lot of developers ask why Lua doesn’t have the var++ or var-- operator to increment or
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. SUBJECT: Condition of Health of Mr. Gustav Krupp von Bohlen 1. Mr. Gustav Krupp von Bohlen was examined by me today, and the following findings are noticed. 2. Subject has suffered from progressive arteriosclerosis and senility since 1939. He suffered an attack of cerebral thrombosis in 1942, which resulted in a temporary facial paralysis. About a year ago he lost bladder and sphincter control. 3. At the present time he is bedridden, has to be fed and to be cared for by nurses. He has no insight into his condition or situation whatsoever and is unable to follow or keep up any conversation. 4. I do not believe that subject can be moved without serious detriment to his health or that interrogation would be of any value due to his loss of speech and complete lack of any understanding. His course will be progressively down-hill. 5. In my judgment subject is not mentally competent to stand trial in a court of justice. /s/ WALTER PICK Capt., MC, 232d Infantry (Attachment II) Blühbach, 13 September 1945 Otto Gerke, M.D. Professor Bad Gastein Medical Certificate Dr. Gustav Krupp von Bohlen und Halbach, born 7 August 1870, has been treated by me for many years; he was examined by me
  • 57. today. Since 1930 there has existed an arthrosis of the spine, as well as a hypotony which as far back as 1932 caused fainting fits. Since 1937 a rapidly increasing sclerosis of the vessels was to be noted which occurred in particular in the vessels of the brain. In 1939 a fleeting paralysis of the eye muscles made its appearance and passing disturbances of speech occured. In the spring of 1942, the patient suffered an apoplectic stroke on the left side, with facialisparosis and a distinct increase of reflexes on the entire right side. The cerebral disturbances of circulation have gradually grown worse despite treatments with medicaments. They manifested themselves first in the form of impaired memory and will power, indecision and general deterioration of intellectual faculties and increased to the point of definite depressions accompanied by apoplectic numbness and involuntary crying. There developed an acute arteriosclerotic dementia. In an automobile accident in December, 1944, the patient suffered a fracture of the nose bone and the skull basis and had to be treated for eight days in the Schwarzach Hospital at St. Veith. Since that time, his physical condition has also deteriorated, and several apoplectic fits have occurred as a consequence of multiple softenings of the brain with heart symptoms and striary syndroms. The patient is by now completely apathetic and disorientated. There exists a motoric aphasy. Owing to rigor of the muscles, he can neither walk nor stand up. For approximately the last six months he has not been able to hold urine and stool. He is completely helpless even in the simplest matters. There can be traced an advanced emphysen in the lungs and a distinct myocardic impairment on the basis of a coronary sclerosis of the heart. An enlargement of the prostate gland has existed for years. The prognosis of the condition is definitely unfavorable, an improvement is not to be expected. Herr Von Bohlen is in no way competent or capable of being interrogated. /s/ DR. GERKE
  • 58. (Attachment III) HEADQUARTERS 42d DIVISION ARTILLERY APO 411 US ARMY 20 October 1945 SUBJECT : Physical Examination of GUSTAV KRUPP VON BOHLEN UND HALBACH TO : General Secretary, International Military Tribunal, APO 403 1. The following history and physical examination of Herr Gustav Krupp von Bohlen und Halbach is submitted in compliance with a request from Mr. James Rowe. The history was obtained from Frau Von Bohlen and from the valet. The information was obtained on the 19th and 20th of October 1945 when the patient was examined at his home at Blühbach, Austria. 2. HISTORY OF PRESENT ILLNESS: Herr Von Bohlen has been developing arteriosclerosis since 1932 according to his physician’s reports. It is believed that he first had a very light apoplectic stroke in 1937. This was very transitory in nature and cleared without noticeable aftereffects except for some loss of the acuteness of his thought processes and memory which his family noticed. In the latter part of November 1944 he had a spell of unconsciousness, fell and fractured a finger and was unable to walk alone for about 24 hours. On 15 December 1944, he was in an automobile accident and received a severe blow and laceration of the forehead. He was hospitalized as a result of this accident until the first week of February 1945, at which time he returned home. Following this he was able to walk only with assistance and he was unable to make coherent statements. He continued to have light strokes and since March has been unable to walk even with help, and his ability to
  • 59. speak has gradually decreased until at the present time he is able only to speak an occasional single word. Also since leaving the hospital he has had no control of the bowels or bladder and during the past three months has given no evidence of recognizing various members of his family or close acquaintances. 3. PHYSICAL EXAMINATION: GENERAL: The patient is an emaciated white male of 76 years of age who is unable to speak or to cooperate in his own examination, and appears to have no realization of what is going on about him. SKIN: Scar 2 inches long extending across the forehead and downward between the eyes and across the bridge of the nose. The skin of the groin is macerated bilaterally as a result of being constantly moistened with urine. EYES, EARS, NOSE AND THROAT: No marked abnormalities. LUNGS: Hyper-resonant throughout with moderate enlargement of the chest cage suggesting the presence of mild emphysema. CARDIOVASCULAR SYSTEM: Apex of heart palpable at a point 1 cm medial to the left mid-clavicular line. No evidence of right heart enlargement could be detected. Pulse 80. Blood pressure 130/75. Pulse full and regular except for an occasional skipped beat. The distal palpable arteries in the wrist and ankles were markedly sclerotic. MUSCULO-SKELETAL SYSTEM: Both legs and arms were slowly moved by the patient although all movements of the extremities were associated with moderate spasticity. The patient was unable to stand alone or walk when he was held upright. NEUROLOGICAL SYSTEM: Pupillary reaction to light normal. Deep tendon reflexes in arms and legs were normal. Normal reaction to plantar stimulation. GENITO-URINARY SYSTEM: Incontinence of urine was noted at the time of examination. Genitalia appeared normal. A prostatic examination was not made. GASTRO-INTESTINAL SYSTEM: Abdominal examination was normal. Incontinence of the bowels was noted at the time of the examination. 4. IMPRESSION AND PROGNOSIS:
  • 60. It is the impression of the undersigned that this man is suffering from far advanced generalized arteriosclerosis which is progressive and that he has already suffered from repeated small apoplectic strokes. It is believed that this condition has already developed to the point where this man has lost all capacity for memory, reasoning or understanding of statements made to him and that transporting or doing anything which might excite him might endanger his life. /s/ PAUL F. CHESNUT Capt., MC Surgeon. ACKNOWLEDGMENT OF SERVICE The following declarations were received in writing from Hans Fritzsche and from Erich Raeder on 18 October 1945: I, Hans Fritzsche, have received today, on 18 October 1945, at 1950 Berlin time, the Indictment of the Chief of Counsel of the International Military Tribunal, a statement regarding my right to defense, a list of German lawyers, the Rules of the International Military Tribunal in the German language. Above documents have been handed to me by the Red Army Officer Grishajeff, acting on orders of the International Military Tribunal and who advised me in the German language on the contents of the documents and on my right to defense. Berlin, 18 October 1945. /s/ HANS FRITZSCHE I, Erich Raeder, have received today, on 18 October 1945, at 1850 Berlin time, the Indictment of the Chief of Counsel of the
  • 61. International Military Tribunal, a statement regarding my right to defense, a list of German lawyers, the Rules of the International Military Tribunal in the German language. Above documents have been handed to me by the Red Army Officer Grishajeff, acting on orders of the International Military Tribunal and who advised me in the German language on the contents of the documents and on my right to defense. Berlin, 18 October 1945. /s/ ERICH RAEDER MOTION ON BEHALF OF DEFENDANT GUSTAV KRUPP VON BOHLEN FOR POSTPONEMENT OF THE TRIAL AS TO HIM Nuremberg, 4 November 1945 Theodor Klefisch Lawyer Cologne, 43, Blumenthalstrasse To : The International Military Tribunal, Nuremberg. As defending counsel to the accused Dr. Gustav Krupp von Bohlen und Halbach I request that the proceedings against this accused be deferred until he is again fit for trial. At any rate I request that the accused be not tried in his absence. Reasons
  • 62. By Article 12 of the Charter of the International Military Tribunal this Court has the right to try an accused in his absence if he cannot be found, or if the Court deem this necessary for other reasons in the interest of justice. The 75-year-old accused Krupp von Bohlen has for a long time been incapable of trial or examination owing to his severe physical and mental infirmities. He is not in a position to be in contact with the outside world nor to make or receive statements. The Indictment was served on him on 19 October 1945 by a representative of the International Military Tribunal by placing the document on his bed. The accused had no knowledge of this event. Consequently he is not aware of the existence of an Indictment. Naturally therefore he is not capable of communicating either with his defense counsel nor with other persons on the subject of his defense. To prove the above two medical certificates are enclosed—that of the court medical expert Doctor Karl Gersdorf of Werfen, Salzburg of 9 September 1945, and that of the Professor Doctor Otto Gerke of Badgastein of 13 September. Lately Herr Krupp von Bohlen has been examined several times by American military doctors. As far as it is possible I should like to request another complete medical examination. If the accused is unable to appear before the Court, then according to Article 12 of the Charter he could be tried only if the Court deemed it necessary in the interests of justice. Whatever may be understood by the phrase “in the interests of justice” it would hardly be objective justice to try a defendant accused of such serious crimes, if he were not informed of the contents of the accusations or if he were not given the chance to conduct his own defense or instruct a defense counsel. Particularly is he in no condition to comprehend the following rights of an accused set out in the Charter: 1. By Article 16, Section (a) of the Charter a copy of the Indictment in a language which he understands will be served on the accused at a suitably appointed time. The assurance given hereby for a sufficient preparation of the proceedings can not be guaranteed to Defendant Krupp von Bohlen on account of his state of disease.
  • 63. According to Section (c) of the same Article 16 a preliminary interrogation of the defendant shall take place in a language intelligible to him. That is likewise impossible here. According to Section (d) of Article 16 the defendant moreover can not exercise his right of decision as to whether he will conduct his own defense or whether he would like to be defended by counsel. Also the right of the defendant as provided in Section (c) of producing evidence and of cross examining witnesses himself or by his counsel in his behalf can not be exercised by the defendant in view of his condition. 2. In the same manner as the Defendant Gustav Krupp von Bohlen und Halbach is not able to exercise the confirmed rights stated above in the preliminary proceedings he will also not be able to exercise in the Trial those rights guaranteed to him by Article 24 of the Charter. In the first place this concerns the statement which the accused has to render on inquiry as to whether he admits his guilt or not, a statement which is of particular importance for the course of the Trial and for the decision of the Tribunal. This is all the more important as this statement regarding guilt or innocence can be made exclusively by the accused himself according to his own judgment and after examining his conscience. So far as the procedure is admissible at all, the defense counsel could not at the request of the Court express himself on the question of guilt, as such a declaration presupposes the possibility of communication and understanding with the accused. Also the defendant could not exercise the right to the last word to which he is entitled according to Article 24, Section (j). The legislators who set up these guarantees for the defense cannot wish to deny them undeservedly to an accused who can not make use of them owing to illness. If by Article 12 of the Charter the Trial of an absent defendant is allowed, then this exception to the rule can be applied only to a defendant who is unwilling to appear though able to do so. As is the case with the criminal procedure rules of nearly all countries, it is on this principle that the rules and regulations concerning the trial of absent defendants are based. /s/ KLEFISCH
  • 64. Lawyer Medical Certificates Attached to Motion on Behalf of Defendant Gustav Krupp von Bohlen (Attachment I) Doctor’s Certificate Dr. Gustav Krupp von Bohlen und Halbach, born 7 August 1870, presently residing at Posthaus Blühbach, Werfen, Salzburg, suffers from progressive arteriosclerotic softening of the brain (Paralysis celebri) and as a consequence of this illness he requires constant care and treatment. He is incapable of standing trial or of being subjected to interrogation. An improvement of his condition is not to be expected. Owing to his bad general physical condition (Myodegeneratio cordis and Ataxis) he is not capable of traveling either. /s/ KARL GERSDORF, M. D. District Doctor Werfen, Salzburg Certified Court Expert Werfen, 8 September 1945 (Attachment II)
  • 65. Attachment II is a medical certificate by Dr. Otto Gerke, printed on page 120 ante. REPORT OF MEDICAL COMMISSION APPOINTED TO EXAMINE DEFENDANT GUSTAV KRUPP VON BOHLEN[15] 7 November 1945 We, the undersigned, during the morning of 6 November 1945, examined the patient, identified as Gustav Krupp von Bohlen by the military authorities in charge, in the presence of his wife and nurse. We unanimously agree that the patient was suffering from: Senile softening of the brain, selectively affecting the frontal lobes of the cerebral cortex and the corpus striatum, due to vascular degeneration. It is our unanimous, considered, professional opinion that the mental condition of the patient, Gustav Krupp von Bohlen, is such that he is incapable of understanding court procedure, and of understanding or cooperating in interrogation. The physical state of the patient is such that he cannot be moved without endangering his life. We are of the considered opinion that his condition is unlikely to improve, but rather to deteriorate even further. Therefore, we unanimously believe that he will never be fit, mentally or physically, to appear before the International Military Tribunal. /s/ R. E. TUNBRIDGE Brigadier, O.B.E., M.D., M.Sc., F.R.C.P.
  • 66. Consulting Physician, British Army of the Rhine /s/ RENE PIEDELIEVRE M.D., Professor of the Paris Faculty of Medicine; Expert of the Tribunal /s/ NICOLAS KURSHAKOV Professor of Medicine, Medical Institute of Moscow Chief Internist, Commissariat of Public Health, U.S.S.R. /s/ EUGENE SEPP Emeritus Professor of Neurology, Medical Institute of Moscow Member, Academy of Medical Sciences, U.S.S.R. /s/ EUGENE KRASNUSHKIN M. D., Professor of Psychiatry, Medical Institute of Moscow /s/ BERTRAM SCHAFFNER Major, Medical Corps Neuropsychiatrist, Army of the United States [15] At a meeting of the International Military Tribunal on 30 October 1945, “it was agreed that a committee of four medical officers, one appointed by each Member of the Tribunal, be sent, if the Committee of Prosecutors made no objection, to examine Krupp and that they be empowered to employ specialists if necessary.” The report of this Medical Commission was presented 7 November 1945. Report of the Medical Examination of Herr Gustav Krupp von Bohlen
  • 67. 1. History: The following information was obtained by questioning Frau Krupp von Bohlen, wife of the patient, Herr Krupp’s valet, and Frl. Krone, private secretary of the patient. The patient had been physically a very active man. He hunted, rode and played tennis. With the aid of guides, he was hunting deer as recently as 1943. He was abstemious in his personal habits, did not smoke or partake of alcohol. He retired to bed early, rarely remaining up after 2200 hours. He had eight children, six sons and two daughters. There is no family history of mental disorder or of drug addiction. Previous Illness: There is no history of any major illness. Since 1930, he has taken spa treatment each year for arthritis of the spine and for hypotension. No radiographs were available to indicate the true pathology of the spinal condition. The valet stated that the patient, on the recommendation of his physicians, had been very careful with his diet during the past ten years. Present Illness: For several years, the patient had been subject to giddy attacks. In consequence, his wife was always anxious when he went hunting, lest he should have an attack whilst on the edge of a cliff, and fall and kill himself. Two reliable guides always accompanied him on his hunting excursions, and in 1942 Frau Krupp also joined in expeditions in order to watch him. Four years ago, the patient had a disturbance of vision primarily due to dysfunction of the eye muscles. For a period he had double vision. From this illness, he made an apparent complete recovery. Two years ago he had a stroke, with weakness of the left side of the face, and impaired function of the right side of the body. Following the latter incident, impairment of gait, general weakness, and impairment of mental functions became increasingly apparent. From the middle of 1944 onwards, the patient became more and more dependent
  • 68. upon his wife; she was the only person who seemed to understand fully his speech and his needs. On November 25th, 1944, he was proceeding from the garden towards the house, and suddenly seemed to run (propulsion gait). Just before reaching the house, he fell and injured his arm. As a result of this accident, he attended the local hospital for treatment, traveling by motor-car. On December 4th, whilst traveling to the hospital at Schwarzach-St. Veith, and asleep in the back of the car, the driver was compelled to swerve to avoid another vehicle, and to brake suddenly. Herr Krupp von Bohlen was thrown forward, and hit his forehead and the bridge of the nose against a metal rail behind the driver’s seat. He did not lose consciousness, but his condition was such that he was detained in the hospital for approximately eight weeks. During his stay in the hospital, he recognized his wife, his relatives and the members of his staff, and spoke to them, albeit haltingly. Since the accident mentioned above, the general condition of the patient has deteriorated rapidly. The members of his staff had increasing difficulty in understanding him. At first, with the aid of two people, he was able to walk a few steps; until two months ago he sat for short periods in a chair. The assistance of men-servants was necessary for this task. He has been incontinent of feces and urine since returning from the hospital in February 1945. Since this date he has only spoken an occasional single word, the words being simple ones and without any rational association, apart from sporadic expletives, such as “Ach, Gott” and “Donner Wetter”, when disturbed. At times he has been exceedingly irritable and on occasions has had inexplicable bouts of weeping. During the past two months, he has become increasingly apathetic, and no longer recognized relatives or friends. Frau Von Bohlen thinks he may still recognize her as a familiar face, but he exhibits no emotional reaction to her
  • 69. presence. She thinks he realizes occasionally that strangers are in the room; e. g., members of the Allied services, and responds by being very tense. Frl. Krone, secretary to the patient, stated that on returning to Blühbach in September 1944, after an absence since May 1944, she could no longer take down letters as dictated by Krupp von Bohlen. Normally he was a very punctilious man, and his diction and writing were correct and very precise. She stated that after September 1944 there were frequent interruptions in his flow of ideas, his syntax was faulty, and he occasionally did not appear to appreciate the meaning of certain words. She would get an idea of what he wanted to say, and then wrote the letter herself in accordance with what she understood to be his wishes. His handwriting also became increasingly illegible, and he had difficulty in signing his name when giving power of attorney to his relatives in January 1945. The valet had been personal valet to Krupp for 20 years, and traveled all over the world with him. He described his master as a very active man, physically and mentally, extremely punctilious in all personal details. He took a great interest in his clothes, and was very observant of any slight defect. In his personal habits he was abstemious, never taking alcohol, and was also a non-smoker. Although a very excellent sportsman and physically capable of considerable feats of endurance when hunting, playing tennis or climbing, he never overdid things and took care of himself without in any way being overanxious about his health. The valet first began to notice serious changes in the patient’s personal habits two years ago, although in the valet’s opinion, he had been failing slightly for about four to five years. The degree of change, however, prior to two years ago, was so slight and his master was in his opinion such a “superman”, that the changes would not have been apparent to the casual observer. Two years ago he began to lose interest in the details of his personal clothing and to
  • 70. become careless with his table manners. For instance, when soup was served to him one day, he took his soup- spoon and used it to take water from his wine-glass. Latterly, he would sit at table and ask who was present, although the only people in the room were intimate members of his family. He would complain that the telephone bell was ringing, and of people speaking to him; these hallucinations became more frequent during the latter part of 1944. The valet was employed as caretaker of the main house by the American Military Government after the cessation of hostilities in Europe, and did not see his employer regularly after June 1945. On August 7, 1945, the occasion of Gustav Krupp von Bohlen’s birthday, he called to pay his respects, and for the first time he was not recognized, and his master showed no appreciation of his presence or his conversation. 2. General Appearance: The patient was lying rigidly in bed in a Parkinsonian position with fine tremors of the jaw and hands. The skin was atrophic and dry, and there was pigmentation of the dorsum of the hands. The temporal arteries were prominent and tortuous. The face was masklike, with dilated venules over the cheeks. There was evidence of considerable wasting of the body tissues, especially in the extremities, which also showed evidence of trophic and acrocyanotic changes. 3. Neuropsychiatric Examination: The patient lay in bed with a masklike face and in a fixed position on his back. The legs were partially flexed, and similarly the elbows, the latter being pressed firmly against the trunk. There was generalized muscular rigidity, due to hypertenus of an extra-pyramidal tract lesion. On the physicians’ entering the room, the patient fixed his gaze on them, and replied to their greeting with “Guten Tag,” and gave his hand when they offered theirs to him. He shook hands normally, but he could not relax his hold or remove his hand, and continued to squeeze the physician’s
  • 71. hand; this was due to the presence of a forced grasp-reflex, which was more marked in the left than in the right hand. When asked how he felt, he replied “Gut,” but to all further questions he gave no reply at all. He was silent and showed no reaction to, or comprehension of, other questions, and simple commands, such as “Open your mouth,” “Put out your tongue,” “Look this way.” Only painful and disagreeable stimuli produced any reaction, and then it was merely a facial expression of discontent, sometimes accompanied by grunts of disapproval. The disturbance of verbal response was not due to dysarthria, because the patient was able to pronounce such words as he did use, quite distinctly. Neither was it due to motor aphasia, because the few words he used were used correctly, and he never exhibited the jargon responses of the true aphasic when attempting to answer questions. The patient was indifferent, apathetic, and was not in good rapport with the external world, lacked initiative, exhibited paucity of emotion. He uttered no spontaneous speech, and his reaction to painful stimuli was primitive. Neurological examination showed the following additional abnormal findings: There was a right facial weakness of a supranuclear origin. The pupils reacted promptly to light, and appeared normal, save that the left was slightly larger than the right. Ophthalmoscopic examination of the fundi, limited by lack of cooperation from the patient, showed clear media and normal retina and retinal vessels. The right disc, the only one visualized, appeared normal. Extra-ocular movements could not be tested; there was no obvious strabismus. All deep reflexes in the arms and legs were present and very brisk. Clonus was not elicited. The plantar reflexes were flexor. Abdominal reflexes were absent, except for the right upper. There was incontinence of urine and feces, of the type associated with senile dementia. There was an associated minimal degree of intertrigo. Owing to lack of cooperation
  • 72. of the patient a full sensory examination could not be made, but the patient responded to pin-prick, deep pressure and muscular movement throughout the body. 4. Cardio-vascular Examination: Pulse: Rate 100, rhythm irregular. The irregularity was due to extra-systoles. The radial arteries were just palpable, without evidence of pathological thickening or tortuosity. Blood pressure: systolic 130 mm. of mercury, diastolic 80 mm. of mercury. Heart: The heart was clinically not enlarged. The cardiac sounds were feeble, there was no accentuation of the second sound in the aortic area, nor were any cardiac murmurs audible. There were no vascular changes observable in the vessels of the fundi. There was no evidence of cedema or of congestive heart failure. 5. Respiratory Examination: Chest movement satisfactory. There was no impairment of percussion noted. Auscultation revealed no impairment of air entry, no alteration in the breath sounds, and the absence of any adventitious sounds. 6. Alimentary-renal Examination: There was slight distention of the abdomen, due to increase in the gaseous content of the intestines. There was no evidence of ascites. The spleen was not palpable, nor was there any evidence of glandular enlargement. The liver was just palpable, one finger’s breadth below the right costal margin, but there was no evidence of enlargement upwards. Urinalysis: no sugar or albumen present. 7. Skeletal Examination: The patient’s rigidity limited the examination of joints. There was limitation of movement of the neck due to muscular hypertonus. The hypertonus was so marked in the lower dorsal and lumbar region as to produce rigidity of the spine. Attempts to move the joints passively stimulated
  • 73. involuntary contractures of the muscles. There was evidence of crepitus in both knee-joints. DISCUSSION: The clinical record presented by this patient is that of an organic cerebral disorder, with predominant involvement of the frontal lobes and basal ganglia. The mental disintegration of the patient renders him incapable of comprehending his environment, and of reacting normally to it. He remains uniformly apathetic and disinterested, intellectually retarded to a very marked degree, and shows no evidence of spontaneous activity. The above findings are such as are found in the degenerative changes associated with senility. The findings in the visceral organs are likewise compatible with the diagnosis of senile degeneration. The clinical course, from the evidence obtained, has been that of a gradual decline over a period of years, with more rapid deterioration during the past year. Such deterioration will continue, and would be rapidly accelerated, with immediate danger to the patient’s life, were he to be moved from his present location. DIAGNOSIS: Senile degeneration of the brain tissues, selectively affecting the frontal lobes of the cerebral cortex and the basal ganglia, with associated senile degeneration of the visceral organs. /s/ R. E. TUNBRIDGE Brigadier, O.B.E., M.D., M.Sc., F.R.C.P., Consulting Physician, British Army of the Rhine
  • 74. /s/ RENE PIEDELIEVRE M.D., Professor of the Paris Faculty of Medicine, Expert of the Tribunal /s/ NICOLAS KURSHAKOV M.D., Professor of Medicine, Medical Institute of Moscow, Chief Internist, Commissariat of Public Health U.S.S.R. /s/ EUGENE SEPP M.D., Emeritus Professor of Neurology, Medical Inst, of Moscow; Member, Academy of Medical Sciences, U.S.S.R. /s/ EUGENE KRASNUSHKIN M.D., Professor of Psychiatry, Medical Institute of Moscow. /s/ BERTRAM SCHAFFNER Major, Medical Corps, Neuropsychiatrist, Army of the United States ANSWER OF THE UNITED STATES PROSECUTION TO THE MOTION ON BEHALF OF DEFENDANT GUSTAV KRUPP VON BOHLEN INTERNATIONAL MILITARY TRIBUNAL THE UNITED STATES OF AMERICA, THE FRENCH REPUBLIC, THE UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND,
  • 75. and THE UNION OF SOVIET SOCIALIST REPUBLICS — against — HERMANN WILHELM GÖRING, et al., Defendants. ANSWER FOR THE UNITED STATES TO THE MOTION FILED IN BEHALF OF KRUPP VON BOHLEN The United States respectfully opposes the application on behalf of Gustav Krupp von Bohlen und Halbach that his trial be “deferred until he is again fit for trial.” If the Tribunal should grant this application, the practical effect would be to quash all proceedings, for all time, against Krupp von Bohlen. It appears that Krupp should not be arrested and brought to the court room for trial. But the plea is that the Tribunal also excuse him from being tried in absentia. This form of trial admittedly is authorized by Article 12 of the Charter of the Tribunal. Of course, trial in absentia in circumstance of the case is an unsatisfactory proceeding either for prosecution or for defense. But the request that Krupp von Bohlen be neither brought to court nor tried in his absence is based on the contention that “the interests of justice” require that he be thus excused from any form of trial. Public interests, which transcend all private considerations, require that Krupp von Bohlen shall not be dismissed unless some other representative of the Krupp armament and munitions interests be substituted. These public interests are as follows: Four generations of the Krupp family have owned and operated the great armament and munitions plants which have been the chief source of Germany’s war supplies. For over 130 years this family has been the focus, the symbol, and the beneficiary of the most sinister forces engaged in menacing the peace of Europe. During the period between the two World Wars, the management of these enterprises was chiefly in Defendant Krupp von Bohlen. It was at all times
  • 76. however a Krupp family enterprise. Only a nominal owner himself, Von Bohlen’s wife, Bertha Krupp, owned the bulk of the stock. About 1937 their son, Alfried Krupp, became plant manager and was actively associated in the policy making and executive management thereafter. In 1940 Krupp von Bohlen, getting on in years, became chairman of the board of the concern, thus making way for Alfried who became president. In 1943 Alfried became sole owner of the Krupp enterprises by agreement between the family and the Nazi Government, for the purpose of perpetuating this business in Krupp family control. It is evident that the future menace of this concern lies in continuance of the tradition under Alfried, now reported to be an internee of the British Army of the Rhine. To drop Krupp von Bohlen from this case without substitution of Alfried, drops from the case the entire Krupp family, and defeats any effective judgment against the German armament makers. Whether this would be “in the interests of justice” will appear from the following recital of only the most significant items of evidence now in possession of the United States as to the activities of Krupp von Bohlen in which his son, Alfried, at all times aided as did other associates in the vast armament enterprises, all plotting to bring about the second World War, and to aid in its ruthless and illegal conduct. After the first World War, the Krupp family and their associates failed to comply with Germany’s disarmament agreements but all secretly and knowingly conspired to evade them. In the 1 March 1940 issue of the Krupp Magazine, the Defendant Krupp stated: “I wanted and had to maintain Krupp in spite of all opposition, as an armament plant for the later future, even if in camouflaged form. I could only speak in the smallest, most intimate circles, about the real reasons which made me undertake the changeover of the plants for certain lines of production . . . . Even the Allied snoop commissioners were duped . . . . After the accession to power of Adolf Hitler, I had the satisfaction of reporting to the Führer that
  • 77. Krupp stood ready, after a short warming-up period, to begin rearmament of the German people without any gaps of experience . . . .” Krupp von Bohlen (and Alfried Krupp as well) lent his name, prestige and financial support to bring the Nazi Party, with an avowed program of renewing the war, into power over the German State. On 25 April 1931 Von Bohlen acted as chairman of the Association of German Industry to bring it into line with Nazi policies. On 30 May 1933 he wrote to Schacht that: “It is proposed to initiate a collection in the most far- reaching circles of German industry, including agriculture and the banking world, which is to be put at the disposal of the Führer of the NSDAP in the name of ‘The Hitler Fund’ . . . . I have accepted the chairmanship of the management council.” Krupp contributed from the treasury of the main Krupp company 4,738,446 marks to the Nazi Party fund. In June 1935 he contributed 100,000 marks to the Nazi Party out of his personal account. The Nazi Party did not succeed in obtaining control of Germany until it obtained support of the industrial interests, largely through the influence of Krupp. Alfried first became a Nazi Party member and later Von Bohlen did also. The Krupp influence was powerful in promoting the Nazi plan to incite aggressive warfare in Europe. Krupp von Bohlen strongly advocated and supported Germany’s withdrawal from the Disarmament Conference and from the League of Nations. He personally made repeated public speeches approving and inciting Hitler’s program of aggression: On 6 and 7 April 1938 two speeches approved annexation of Austria; on 13 October 1938 approving Nazi occupation of the Sudetenland; on 4 September 1939 approving the invasion of Poland; on 6 May 1941 commemorating success of Nazi arms in the West. Alfried Krupp also made speeches to the same general effect. Krupps were thus one of the most persistent and influential forces that made this war.
  • 78. Krupps also were the chief factor in getting ready for the war. In January 1944, in a speech at the University of Berlin, Von Bohlen boasted, “Through years of secret work, scientific and basic groundwork was laid in order to be ready again to work for the German Armed Forces at the appointed hour without loss of time or experience.” In 1937, before Germany went to war, Krupps booked orders to equip satellite governments on approval of the German High Command. Krupp contributed 20,000 marks to the Defendant Rosenberg for the purpose of spreading Nazi propaganda abroad. In a memorandum of 12 October 1939 a Krupp official wrote offering to mail propaganda pamphlets abroad at Krupp expense. Once the war was on, Krupps, both Von Bohlen and Alfried being directly responsible therefor, led German industry in violating treaties and international law by employing enslaved laborers, impressed and imported from nearly every country occupied by Germany, and by compelling prisoners of war to make arms and munitions for use against their own countries. There is ample evidence that in Krupp’s custody and service they were underfed and overworked, misused, and inhumanly treated. Captured records show that in September 1944 Krupp concerns were working 54,990 foreign workers and 18,902 prisoners of war. Moreover, the Krupp companies profited greatly from destroying the peace of the world through support of the Nazi program. The rearmament of Germany gave Krupp huge orders and corresponding profits. Before this Nazi menace to the peace began, the Krupps were operating at a substantial loss. But the net profits after taxes, gifts, and reserves steadily rose with rise of Nazi rearmament, being as follows: For year ending 30 September 1935— 57,216,392 marks For year ending 30 September 1938— 97,071,632 marks For year ending 30 September 1941— 111,555,216 marks The book value of the Krupp concerns mounted from 75,962,000 marks on 1 October 1933, to 237,316,093 marks on 1 October 1943. Even this included many going concerns in occupied countries at a book value of only 1 mark each. These figures are subject to the
  • 79. adjustments and controversies usual with financial statements of each vast enterprise but approximately reflect the facts about property and operations. The services of Alfried Krupp and of Von Bohlen and their family to the war aims of the Nazi Party were so outstanding that the Krupp enterprises were made a special exception to the policy of nationalization of industries. Hitler said that he would be “prepared to arrange for any possible safeguarding for the continued existence of the works as a family enterprise; it would be simplest to issue ‘lex Krupp’ to start with”. After short negotiations, this was done. A decree of 12 November 1943 preserves the Krupp works as a family enterprise in Alfried Krupp’s control and recites that it is done in recognition of the fact that “for 132 years the firm of Fried. Krupp, as a family enterprise has achieved outstanding and unique merits for the armed strength of the German people.” It has at all times been the position of the United States that the great industrialists of Germany were guilty of the crimes charged in this Indictment quite as much as its politicians, diplomats, and soldiers. Its chief of counsel, on 7 June 1945, in a report to President Truman, released by him and with his approval, stated that the accusations of crimes include individuals in authority in the financial, industrial, and economic life of Germany as well as others. Pursuant thereto, the United States, with approval of the Secretary Of State, proposed to indict Alfried Krupp, son of Krupp von Bohlen, and president and owner of the Krupp concern. The Prosecutors representing the Soviet Union, the French Republic, and the United Kingdom unanimously opposed inclusion of Alfried Krupp. This is not said in criticism of them or their judgment. The necessity of limiting the number of defendants was considered by representatives of the other three nations to preclude the addition of Alfried Krupp. Immediately upon service of the Indictment, learning the serious condition of Krupp von Bohlen, the United States again called a meeting of Prosecutors and proposed an amendment to include Alfried Krupp. Again the proposal of the United States was defeated by a vote of 3 to 1. If now the Tribunal shall exercise its discretion to excuse from trial the one indicted member of the Krupp
  • 80. family, one of the chief purposes of the United States will be defeated and it is submitted that such a result is not “in the interests of justice.” The United States respectfully submits that no greater disservice to the future peace of the world could be done than to excuse the entire Krupp family and the armament enterprise from this Trial in which aggressive war making is sought to be condemned. The “interests of justice” cannot be determined without taking into account justice to the men of four generations whose lives have been taken or menaced by Krupp munitions and Krupp armament, and those of the future who can feel no safety if such persons as this escape all condemnation in proceedings such as this. While of course the United States cannot, without the concurrence of one other Power indict a new defendant, it can under the Charter alone oppose this motion. The United States respectfully urges that if the favor now sought by Krupp von Bohlen is to be granted, it be upon the condition that Alfried Krupp be substituted or added as a defendant so that there may be a representative of the Krupp interests before the Tribunal. It may be suggested that bringing in a new defendant would result in delay. Admitting, however, that a delay which cannot exceed a few days may be occasioned, it is respectfully suggested that the precise day that this Trial will start is a less important consideration than whether it is to fail of one of its principal purposes. The American Prosecution staff has been by long odds the longest and farthest away from home in this endeavor. On personal as well as public interest consideration it deplores delay. But we think the future as well as the contemporary world cannot fail to be shocked if, in a trial in which it is sought to condemn aggressive war making, the Krupp industrial empire is completely saved from condemnation. The complete trial brief of the United States on Krupp von Bohlen with copies of the documents on which his culpability is asserted will be made available to the Tribunal if it is desired as evidence concerning him and Alfried Krupp and the Krupp concerns. Respectfully submitted:
  • 81. /s/ ROBERT H. JACKSON Chief of Counsel for the United States of America 12 November 1945
  • 82. MEMORANDUM OF THE BRITISH PROSECUTION ON THE MOTION ON BEHALF OF DEFENDANT GUSTAV KRUPP VON BOHLEN British War Crimes Executive (E.S.) 12 November 1945 To: The International Military Tribunal. The British Chief Prosecutor has had the opportunity of considering the application of the Defending Counsel to the accused GUSTAV KRUPP VON BOHLEN UND HALBACH: 1) that the proceedings against this accused be deferred until he is again fit for trial; 2) at any rate, that the accused be not tried in his absence. The British Chief Prosecutor opposes this application for the following reasons: i) The medical position is that as far as can be foreseen the said defendant will never again be fit for trial, and therefore if he is not tried in his absence, he will not be tried at all. ii) Although in an ordinary case it is undesirable that a defendant should be tried when he is unable to comprehend the charges made against him, or to give instruction for his defence, there are special considerations which apply to this case and make it essential for the Defendant Gustav Krupp von Bohlen und Halbach to be tried in his absence. iii) As this is a case of conspiracy, the British Prosecutor submits that all the evidence directly concerned with the actions and speeches of the said defendant and the operations of Fried. Krupp A.G. would be evidence against the remaining defendants, if the Prosecution establishes a prima facie case:
  • 83. a) that the conspiracy existed; b) that the said defendant was a party to the conspiracy. Such prima facie case is clearly indicated in the Indictment lodged with the Tribunal and the evidence against the present defendant set out in the American Answer to this Application. iv) If this submission of the British Chief Prosecutor is correct and this evidence can and will be given in Court, then it is at least arguable that it is preferable for the said defendant to be represented so that his lawyer can deal with such evidence to the best of his ability. v) It is a matter of common knowledge of which the Court may take cognisance that the business of Fried. Krupp A.G. is a vast organisation. There are, therefore, many sources within the Krupp firm from which the defending Advocate can obtain information which will enable him to deal with the allegations contained in the American Answer. If the Defendant Gustav Krupp is not retained in the list of defendants, there will be no advocate so well qualified to deal with those allegations on behalf of the other defendants, against whom they will still be preferred. vi) In the circumstances of this trial the kernel of the case for the prosecution is that a number of conspirators have agreed and worked together for the purpose of waging aggressive war and causing untold misery to the World. The public interest, that the defendant who is responsible for the preparation of armaments on the one hand, and the utilisation on arms production, of prisoners of war and forced labour, including detainees from Concentration Camps on the other, is one of “the interests of justice” within Article 12 of the Charter. vii) Finally, it is earnestly desired that the wishes of the Tribunal as publicly announced at Berlin on the 18th October that the trial should open on the appointed day, namely, 20th November be realised and carried into execution. The British Delegation is strongly opposed to any postponement. /s/ HARTLEY SHAWCROSS
  • 84. British Chief Prosecutor MEMORANDUM OF THE FRENCH PROSECUTION ON THE MOTION ON BEHALF OF DEFENDANT GUSTAV KRUPP VON BOHLEN Nuremberg, 13 November 1945 MEMORANDUM by the French Delegation concerning the matter of Krupp which was discussed at the meeting of 12 November 1945 France is formally opposed to dropping the firm of Krupp from the Trial since the other prosecutors do not contemplate the possibility of preparing at this time a second trial directed against the big German industrialists. France objects therefore to a simple severance. The remaining possibilities are either the trial of Krupp Sr. in absentia or the substitution of Krupp Jr. in his father’s place and stead. The trial of an old man who is about to die and who is not before the Court is difficult in itself. France would prefer to substitute his son against whom there are serious charges. For simple reasons of expediency, France requests that there be no delay in excess of the delay that will result in all probability from the motions of the Defense. If the Tribunal denies these motions of the Defense, the Trial of Krupp Sr. should take place in his absence. However, this is in our opinion the lesser of two evils. /s/ DUBOST
  • 85. SUPPLEMENTAL MEMORANDUM OF THE FRENCH PROSECUTION Nuremberg, 14 November 1945 ADDITIONAL MEMORANDUM We consider the trial of KRUPP, the father, as impossible under the circumstances. The trial of an old, dying man, absent from the dock, cannot take place. We wish that the son be prosecuted. There are serious charges against him. We had requested, so far, that he be prosecuted without any delay arising in the Trial therefrom. The reasons of opportunity which had induced us to adopt this attitude are no longer so imperative since the Soviet Delegation has concurred in Mr. Jackson’s thesis. Consequently we no longer raise any objection and we concur ourselves in this thesis. The Deputy-Delegate of The French Government in the Prosecution of The International Military Tribunal /s/ CH. DUBOST ORDER OF THE TRIBUNAL GRANTING POSTPONEMENT OF PROCEEDINGS AGAINST GUSTAV KRUPP VON BOHLEN
  • 86. INTERNATIONAL MILITARY TRIBUNAL THE UNITED STATES OF AMERICA, THE FRENCH REPUBLIC, THE UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND, and THE UNION OF SOVIET SOCIALIST REPUBLICS — against — HERMANN WILHELM GÖRING, et al., Defendants. ORDER ON CONSIDERATION of the application of counsel for the defendant, Gustav Krupp von Bohlen, for a postponement of the proceedings against him; IT IS ORDERED that the application for postponement be, and the same hereby is, granted; IT IS FURTHER ORDERED that the charges in the indictment against Gustav Krupp von Bohlen shall be retained upon the docket of the Tribunal for trial hereafter, if the physical and mental condition of the defendant should permit. BY THE INTERNATIONAL MILITARY TRIBUNAL /s/ GEOFFREY LAWRENCE President. Dated this 15th day of November, 1945. ATTEST: /s/ WILLIAM L. MITCHELL General Secretary.
  • 87. SUPPLEMENTARY STATEMENT OF THE UNITED STATES PROSECUTION MEMORANDUM FILED BY THE UNITED STATES CHIEF OF COUNSEL TO THE INTERNATIONAL MILITARY TRIBUNAL The United States, by its Chief of Counsel, respectfully shows: The order of the Tribunal, that “The charges in the Indictment against Gustav Krupp von Bohlen shall be retained upon the docket of the Tribunal for trial hereafter, if the physical and mental condition of the defendant should permit,” requires the United States to make clear its attitude toward subsequent trials, which may have been misapprehended by the Tribunal, in order that no inference be drawn from its silence. The United States never has committed itself to participate in any Four Power trial except the one now pending. The purpose of accusing organizations and groups as criminal was to reach, through subsequent and more expeditious trials before Military Government or military courts, a large number of persons. According to estimates of the United States Army, a finding that the organizations presently accused are criminal organizations would result in the trial of approximately 130,000 persons now held in the custody of the United States Army; and I am uninformed as to those held by others. It has been the great purpose of the United States from the beginning to bring into this one trial all that is necessary by way of defendants and evidence to reach the large number of persons responsible for the crimes charged without going over the entire evidence again. We, therefore, desire that it be a matter of record that the United States has not been, and is not by this order, committed to participate in any subsequent Four Power trial. It reserves freedom to determine that question after the capacity to handle one trial under difficult conditions has been tested. Respectfully submitted: /s/ ROBERT H. JACKSON
  • 88. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com