Lua Extending References:

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
David Notkin Autumn 2009 CSE303 Lecture 13 This space for rent.
References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters (primarily) 2. “Lua Reference Manual” (included in Lua installation.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Guide To UNIX Using Linux Third Edition
Recitation 1 Programming for Engineers in Python.
References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters “Lua Reference Manual” (included in Lua installation or online)
Copyright 2007, Information Builders. Slide 1 Maintain & JavaScript: Two Great Tools that Work Great Together Mark Derwin and Mark Rawls Information Builders.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
Introduction to Python
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Using Visual Basic for Applications in Microsoft Project Sean Vogel.
Variables and Functions. Open your Encoder program Let’s begin by opening the “Labyrinth Auto Straight” code. Save this file as Labyrinth with variables.
CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Python Let’s get started!.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
Written by: Dr. JJ Shepherd
CSCI 156: Lab 11 Paging. Our Simple Architecture Logical memory space for a process consists of 16 pages of 4k bytes each. Your program thinks it has.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
1 Objective Caml (Ocaml) Aaron Bloomfield CS 415 Fall 2005.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Python C API overview References:
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
Python C API overview References:
String and Lists Dr. José M. Reyes Álamo.
OOP: Creating a Class Topics More OOP concepts
Values vs. References Lecture 13.
Introduction to Computing Science and Programming I
Chapter 2: The Visual Studio .NET Development Environment
Whatcha doin'? Aims: To start using Python. To understand loops.
Intro to ETEC Java.
Practical Office 2007 Chapter 10
Python Let’s get started!.
Containers and Lists CIS 40 – Introduction to Programming in Python
Pamela Moore & Zenia Bahorski
Creating Custom Conversion Themes
Java package classes Java package classes.
CISC/CMPE320 - Prof. McLeod
Microsoft Access Illustrated
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Important terms Black-box testing White-box testing Regression testing
COMPUTER 2430 Object Oriented Programming and Data Structures I
Important terms Black-box testing White-box testing Regression testing
CS313D: Advanced Programming Language
Computer Science 210 Computer Organization
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
1. Open Visual Studio 2008.
String and Lists Dr. José M. Reyes Álamo.
Tonga Institute of Higher Education
Python programming exercise
Building Java Programs
CISC101 Reminders All assignments are now posted.
Java Programming Language
Lab4 problems More about templates Some STL
Quiz Points 1 Rules Raise your hand if you know the question
Topics Introduction to File Input and Output
CSS161: Fundamentals of Computing
Corresponds with Chapter 5
Presentation transcript:

Lua Extending References: “Programming in LUA, 2nd ed.”, Roberto Lerusalmschy Chapters 24-28 “Lua Reference Manual” (included in Lua installation or online)

Overview Write a module (in C) that can be run in Lua. Lua “world”  C “world” Lua Makes heavy use of a virtual stack No Lua/C types Lua does all the memory management without our help. Python: Reference counting (helping Python with memory mgmt) A ton of conversion functions Many Py_xyz/C types. We’ll explore most of the techniques needed to embed a Lua interpreter in ssuge.

Font / Color conventions -- lua code… print(“Lua code”) -- lua comment // C code printf(“%s”, “C-code”); // C comment #define LS lua_State * L int lua_gettop(lua_State * L); int lua_gettop(LS); // short-hand.

Simple Example We’ll create a module (dll in windows): A variable A function A simple class The module itself is useless, but it illustrates Converting between Lua and C data Using things in a different “universe” Simpler than the lab I had planned Embedding lua in ssuge I’ll save that for Lab1 in ETGG3802

Step1: Create the project [Do it together] Remember to remove the release and x64 In the real lab, I don’t want you to include all lua.c files in the project! Test program v 1.0 [Do it!] What we just did: Created a new (empty) module on the Lua Stack and returned it to the lua interpreter (lua_State*) -- test01.lua local m = require “test“ -- [discuss search]

Step1, cont. Run it! Sources of errors: Make sure the .dll is in same folder as .lua … Visual C++ debugger doesn’t work! Lua doesn’t really have a debugger OK, it sort of does, but… …it can’t inspect C code. My (bad) solution: Lots of printf statements!

Lua State object The environment When running Lua on the command line There is one lua_State * object It is passed to all C code run through the command line interpreter. Later (in ssuge, next semester), we'll create a single state (the "Lua World") lua_State * luaL_newstate();

Using the documentation Your best friend in this lab… https://www.lua.org/manual/5.3/ (Scroll down a bit to the Index) # items popped from stack # items pushed onto stack One of these: “-” never raises an error “m” could raise out-of-mem error “e” could raise an error “v” could raise an error on purpose

Lua Stack The way data is exchanged between C and Lua. Indices: 1 to n: first, second, …, last -1 to –n: last, next-to-last, …, first “meta” (virtual) indices – not really on stack. Globals Registry …

Step2: test program, v2.0 Requires us to add (C) function(s) and add them to the module [Do it!] -- test02.lua local m = require “test" print(m.adder(5, 3)) -- 8 print(m.adder(5.2, 3.1)) -- 8.3 print(m.adder(“abc”, 5)) -- error

Functions to manipulate the stack // Gets the top (i.e. the number // of things on the stack.) int lua_gettop(LS); // Removes elements (or add’s nils) // to resize the stack void lua_settop(LS, int num); // Pushes a copy of the indexed value // to the top of the stack void lua_pushvalue(LS, int index);

Functions to manipulate the stack, cont. // Removes the indexed value and // collapses the “hole”. int lua_remove(LS, int index); // Moves the top element to the given // index. void lua_insert(LS, int index); // Pops the top value and replaces the // value at the given index with it void lua_replace(LS, int index);

Functions to get values int lua_isnumber(LS, int index); int lua_tointeger(LS, int index); double lua_tonumber(LS, int index); int lua_isstring(LS, int index) char * lua_tostring(LS, int index); Another method: int luaL_checkint(LS, int index); // error-check char * luaL_checkstring(LS, int index)

Functions to add values to the stack lua_pushinteger(LS, int val); lua_pushnumber(LS, double val); lua_pushstring(LS, char * val); …

A handy debugging tool void stack_dump(lua_State * L) { int i; char type_str[256], value_str[256]; printf("===========\n|STACK DUMP\n===========\n"); for (i=1; i<=lua_gettop(L); i++) value_str[0] = '\0'; if (lua_isboolean(L, i)) sprintf_s(type_str, 255, "boolean"); if (lua_toboolean(L, i))sprintf_s(value_str, 255, "true"); else sprintf_s(value_str, 255, "false"); } else if (lua_iscfunction(L, i))sprintf_s(type_str, 255, "cfunction"); else if (lua_isfunction(L, i))sprintf_s(type_str, 255, "lua-function"); else if (lua_islightuserdata(L, i))sprintf_s(type_str, 255, "lt-user-data"); else if (lua_isnil(L, i))sprintf_s(type_str, 255, "nil"); else if (lua_isnone(L, i))sprintf_s(type_str, 255, "<none>");

A handy debugging tool, cont. else if (lua_isnumber(L, i)) { sprintf_s(type_str, 255, "number"); sprintf_s(value_str, 255, "%f", lua_tonumber(L, i)); } else if (lua_isstring(L, i)) sprintf_s(type_str, 255, "string"); sprintf_s(value_str, 255, "%s", lua_tostring(L, i)); else if (lua_istable(L, i))sprintf_s(type_str, 255, "table"); else if (lua_isuserdata(L, i))sprintf_s(type_str, 255, "user-data"); printf("|\t[%d]: type='%s', value='%s'\n", i, type_str, value_str); } // end the for loop printf("===========\n|END STACK DUMP\n===========\n");

Step3: test program, v3.0 local m = require("lua_extending") --print(m.adder(5, 3)) --print(m.adder(5.2, 3.1)) --print(m.adder("abc", 5)) --for k, v in pairs(m) do -- print(k .. " " .. tostring(v)) --end x = m.Complex.new(4.2, 3.7) y = m.Complex.new(1.9, -0.2) z = m.Complex.new() q = m.Complex.new("surprise-me") print(z) -- <0.0, 0.0i> z = nil -- Triggers g.c. on z print(x) -- <4.2, 3.7i> print(q) -- A random complex with values 0.0 ... 1.0 print(x + y) -- <6.1, 3.5i> print(x:magnitude()) -- 5.5973205566406

Review: metatables Any table (call it A) can optionally have a meta-table (call it MT) A metatable can hold special meta-methods __index(table, key): called if we try to use a non-existent field in A __newindex(table, key, value): similarly if we try to modify a non-existent field in A __tostring(table): convert to a string __add(lhs, rhs): used when using + __gc(table): called when the table is “destroyed”. … lua-users.org/wiki/MetatableEvents For OOP, we set the metatable of instances to the class table.

Step5: Create the Complex “class" back-end 3 sub-steps Create the C structure Create methods Associate this new class with the module [Do it!]