הסבת מלאי ל-C
שיעור 47 מתוך 48 בקורס Lua למפתחי C של Coddy.
אתגר
בינוניגרסת C מחזיקה מערך דינמי של רשומות ושם שהוקצה בנפרד לכל רשומה. היא משחררת את ההקצאות האלה לאחר הדיווח. טבלאות Lua מחליפות את ניהול האחסון הזה; יש לשמר את התנהגות הצבירה והמיון.
העבירו את תוכנית הייחוס ב-C למודולים של Lua. כל שורת קלט מכילה שם באותיות ASCII קטנות, נקודתיים והפרש שלם עם סימן. צברו לפי שם, השאירו רק סכומים סופיים חיוביים, מיינו את השמות בסדר עולה והחזירו רשומות name=total המחוברות בפסיקים. החזירו empty כשלא נשארות רשומות. ממשו את inventory.aggregate(lines) בקובץ inventory.lua; app מעצב את התוצאה. כל שורות הקלט תקינות.
מימוש הייחוס ב-C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <errno.h>
struct Entry { char *name; long total; };
/* The caller owns each returned line, including a final line without newline. */
static int read_line(char **out) {
size_t length = 0, capacity = 32;
char *line = malloc(capacity);
int ch;
if (line == NULL) return -1;
while ((ch = getchar()) != EOF && ch != '\n') {
if (length == capacity - 1) {
if (capacity > SIZE_MAX / 2) { free(line); return -1; }
capacity *= 2;
char *grown = realloc(line, capacity);
if (grown == NULL) { free(line); return -1; }
line = grown;
}
line[length++] = (char)ch;
}
if (ferror(stdin)) { free(line); return -1; }
if (ch == EOF && length == 0) { free(line); return 0; }
line[length] = '\0';
*out = line;
return 1;
}
static int by_name(const void *left, const void *right) {
const struct Entry *a = left, *b = right;
return strcmp(a->name, b->name);
}
int main(void) {
struct Entry *entries = NULL;
size_t count = 0;
int status = 0, result;
char *line = NULL;
while ((result = read_line(&line)) == 1) {
char *separator = strchr(line, ':');
if (separator == NULL || separator == line) { status = 1; break; }
*separator = '\0';
for (const char *p = line; *p != '\0'; ++p)
if (*p < 'a' || *p > 'z') status = 1;
const char *digits = separator + 1;
if (*digits == '-') ++digits;
if (*digits == '\0') status = 1;
for (const char *p = digits; *p != '\0'; ++p)
if (*p < '0' || *p > '9') status = 1;
errno = 0;
char *end;
long delta = strtol(separator + 1, &end, 10);
if (status || errno == ERANGE || *end != '\0') { status = 1; break; }
size_t index = 0;
while (index < count && strcmp(entries[index].name, line) != 0) ++index;
if (index == count) {
if (count == SIZE_MAX / sizeof *entries) { status = 1; break; }
struct Entry *grown = realloc(entries, (count + 1) * sizeof *entries);
if (grown == NULL) { status = 1; break; }
entries = grown;
entries[count++] = (struct Entry){line, 0};
line = NULL; /* Transfer ownership to the new entry. */
}
long old = entries[index].total;
if ((delta > 0 && old > LONG_MAX - delta) ||
(delta < 0 && old < LONG_MIN - delta)) { status = 1; break; }
entries[index].total += delta;
free(line);
line = NULL;
}
if (result < 0) status = 1;
free(line);
if (!status) {
if (count > 1) qsort(entries, count, sizeof *entries, by_name);
int printed = 0;
for (size_t i = 0; i < count; ++i) {
if (entries[i].total > 0) {
printf("%s%s=%ld", printed ? "," : "", entries[i].name, entries[i].total);
printed = 1;
}
}
if (!printed) fputs("empty", stdout);
putchar('\n');
}
for (size_t i = 0; i < count; ++i) free(entries[i].name);
free(entries);
return status || ferror(stdout);
}
ערכו את app.lua, inventory.lua. הקובץ הגלוי והנעול main.lua קורא את stdin לרצף של שורות, קורא ל-app.run(lines) ומדפיס את הערך שהוחזר עם תו שורה חדשה אחד בסוף. אל תדפיסו הודעות אבחון ואל תשנו את שמות המודולים. קלט ריק יוצר רצף ריק. כל הקלטים המספריים קטנים מספיק כדי למנוע גלישה.
בדיקות API ציבוריות: inventory.aggregate(lines) מחזירה טבלה חדשה של הפרשים מסומנים שסוכמו, ומשמרת סכומים שערכם אפס. קלט ריק מחזיר טבלה ריקה. העיצוב והסינון מתבצעים ב-app. מנהל ההתקן הנעול בודק את ההתנהגות הזאת לפני הקריאה ל-app.run. בדיקות אלה אינן מדפיסות דבר כשהן מצליחות.
נסו בעצמכם
-- בדיקות של ה-API הציבורי
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
כל השיעורים ביחידה Lua למפתחי C
1תוכניות Lua ראשונות
הרצת מודולי Luaהדפסה והערותשמות ותחום מקומימספרים והמרהמחרוזות ומיקומי בתיםסיכום: עיצוב קבלה4פונקציות וסגירות
פונקציות וארגומנטיםערכי ברירת מחדל וטבלאות אפשרויותתוצאות מרובות וארגומנטים משתניםפונקציות callback ומצב שנלכדסיכום: פונקציות לתמחורתרגלו בעצמכם: קומפיילר Lua אונליין