<<

ScriptingScripting LanguagesLanguages

Roberto Ierusalimschy MostMost PopularPopular LanguagesLanguages

• TIOBE Programming Community Index • http://www.tiobe.com/tpci.htm • 1 • 2 • 3 C++ • 4 PHP • 5 • 6 (Visual) Basic • 7 C# • 8 Python • 9 JavaScript • 10 Delphi/Kylix Scripting Languages WhatWhat isis aa ScriptingScripting Language?Language?

• A dynamic language • Interpreted • Dynamic typing • Automatic • String manipulation • Secure • Interface to other languages/programs

Scripting Languages DynamicDynamic xx StaticStatic LanguagesLanguages

• Dynamic typing x static typing • Dynamic structures x static structures • Dynamic binding x static binding • Flexibility x robustness • efficiency x efficiency

Scripting Languages InterpretedInterpreted LanguagesLanguages

• Formally, any language can be implemented by an or by a • But not all languages allow self- interpretation through an operator • needs reflexive facilities

Scripting Languages InterpretedInterpreted LanguagesLanguages (2)(2)

• Better error messages • Interactive mode (“console”) • Faster cycle “edit-compile-” • Typically portable • Reflexive facilities

Scripting Languages DynamicDynamic TypingTyping

• But strongly typed! • Type checking run • All languages can have run-time mismatches • x/0 , NULL->x • Concept of type more flexible • (strings), Scheme (lists), Lua (tables)

Scripting Languages AutomaticAutomatic MemoryMemory ManagementManagement

• The biggest single difference • Simplify programming • Simplify Interfaces! • some contempt for efficiency helps too • Avoids several common bugs • buffer overflow • memory-allocation bugs are the second hardest to • Helps dynamic structures

Scripting Languages StringsStrings

• Text provides a natural representation for almost anything • Programs are strings • • Rich and well-studied of operations • regular expressions/ • grammars • Rich set of external tools • editors, filters, etc.

Scripting Languages SecureSecure LanguageLanguage

• Complete • All behavior (including errors) explained within the language • Better error messages • Much easier to debug

Scripting Languages InterfacesInterfaces

• No language is good for everything • Good languages must interact with other languages • Interface must match different worlds • memory management • types

Scripting Languages WhyWhy ScriptingScripting Languages?Languages?

• Programming languages are complex engineering projects • Several compromises • No language is optimal for everything • C is not for everybody • Java is not for every task • A main compromise relates to how dynamic is the language

Scripting Languages WhyWhy ScriptingScripting LanguagesLanguages (2)(2)

• Quick-and-dirt programming • End-user programming • Component Integration

Scripting Languages Quick-and-DirtyQuick-and-Dirty ProgrammingProgramming

• Use-once programs • e.g., data migration • • Rapid prototyping • Programmer = User • ≈ run time

Scripting Languages End-UserEnd-User ProgrammingProgramming

• User = Programmer • Domain-specific languages • Configuration

Scripting Languages ComponentComponent IntegrationIntegration

• “Glue language” • Components change little • written in a hard language • Final applications change much • written in a soft language • Impedance match • type differences, etc.

Scripting Languages ExtensionExtension LanguagesLanguages

• Particular case of scripting languages • Concept created by Ousterhout, with Tcl • Emphasis in inter-language communication • bidirectional calls & references • Duality: who owns the main loop? • extension language • extensive language

Scripting Languages LuaLua

• not totally unlike Perl, Python, Tcl • An extensive extension language • emphasis in inter-language communication • Particular set of goals: • portability • simplicity • small size • “embedability”

Scripting Languages PortabilityPortability

• Runs on most machines we ever heard of • , Windows, Windows CE, Symbian, embedded hardware, Palm, PSII, etc. • Written in ANSI C ∩ ANSI C++ • avoids #ifdefs • avoids dark corners of the standard

Scripting Languages SimplicitySimplicity

• Just one • tables • Just one numerical type • typically double • Mechanisms instead of policies

Scripting Languages SmallSmall SizeSize

• Less than 200K • Core + libraries • clear interface • core has less than 100K • easy to remove libraries

Scripting Languages EmbedabilityEmbedability

• Provided as a • Simple API • simple types • low- operations • stack model • Embedded in C/C++, Java, , C#, Perl, Ruby, Ada, etc.

Scripting Languages HowHow IsIs LuaLua

• Conventional syntax

function fact (n) if n == 0 then return 1 else return n * fact (n - 1) end end

Scripting Languages TablesTables

• Associative arrays • any value as key • referential semantics • Only data-structuring mechanism • Constructors {} {x = 5, y = 10} {“Sun”, “Mon”, “Tue”}

Scripting Languages DataData StructuresStructures

• Tables implement most data structures in a simple and efficient way • records: syntactical sugar t.x for t["x"]:

t = {} t.x = 10 t.y = 20 (t.x, t.y) print(t["x"], t["y"])

Scripting Languages DataData StructuresStructures (2)(2)

• Arrays: integers as indices a = {} for i=1,n do a[i] = 0 end

• Sets: elements as indices

t = {} t[x] = true -- t = t ∪ {x} if t[x] then -- x ∈ t? ...

Scripting Languages LinkedLinked ListsLists

• Tables are objects, created dynamically

list = {value=v, next=list} list old list ...

value - v next -

Scripting Languages StringsStrings

• Immutable values • no size limit • not uncommon programs that read whole file • Can store any binary data • Pattern-matching implemented through library

Scripting Languages FunctionsFunctions

• First-class Values function inc (x) inc = function (x) sugar return x+1 return x+1 end end

• Multiple returns

a, = f() function f() print(f()) return 1,2 end

Scripting Languages ModulesModules

• Tables populated with functions • Several facilities come for free • submodules • local names

local m = require “module” local f = m.foo

Scripting Languages ObjectsObjects

• First-class functions + tables ≈ objects • Syntactical sugar for methods • handles self function a:foo (x) ... end a.foo = function (self,x) ... end

a:foo(x) a.foo(a,x)

Scripting Languages DelegationDelegation

• When a delegates from b, any field absent in a is get from b • a[k] becomes a[k] or b[k] • Allows prototype-based and class-based objects • Allows single inheritance

Scripting Languages ReflexiveReflexive FacilitiesFacilities

• Introspection function clone (t) local new = {} • function type for k,v in pairs(t) do • table traversal new[k] = v end return new end

• Access to global for n in pairs(_G) do table print(n) end

Scripting Languages ReflexiveReflexive FacilitiesFacilities (2)(2)

• Dynamic calls t[1] = a; t[2] = b; f(unpack(t))

• Debug interface • stack • local variables • current line

Scripting Languages Lua-CLua-C APIAPI

• Reentrant library • Impedance mismatch: • dynamic x static typing • automatic x manual memory management • Uses a stack for inter-language communication

Scripting Languages Lua-CLua-C APIAPI (2)(2)

• Load Lua code • in files, strings, etc. • Call Lua functions • Manipulate Lua data • Register of C functions to be called by Lua code

Scripting Languages CommunicationCommunication LuaLua -- CC

• All data exchange through a stack of Lua values

/* calling f("hello", 4.5) */ lua_getglobal(L, "f"); lua_pushstring(L, "hello"); lua_pushnumber(L, 4.5); lua_call(L, 2, 1); if (lua_isnumber(L,-1)) printf("%f\n", lua_getnumber(L, -1));

Scripting Languages CC FunctionsFunctions static int l_sqrt (lua_State *L) { double n = luaL_checknumber(L, 1); lua_pushnumber(L, sqrt(n)); return 1; /* number of results */ }

lua_pushcfunction(L, l_sqrt); lua_setglobal(L, “sqrt”);

Scripting Languages UsesUses ofof LuaLua

• Embedded systems • switches, robots • Scripting • APT-RPM • Niche in games • informal poll by gamedev. (Sep. 2003) showed Lua as the most used language for game scripting

Scripting Languages SomeSome GamesGames ScriptedScripted withwith LuaLua

Scripting Languages BooksBooks

Game Programming with Python, Lua, and Ruby Premier Press, 2003

Programming in Lua Lua.org, 2003

Game Development with Lua Charles River Media, 2005

Scripting Languages ToTo KnowKnow More...More...

www.lua.org

Scripting Languages